Categories
React Answers

How to add a delay onMouseOver event handler with React?

Sometimes, we want to add a delay onMouseOver event handler with React.

In this article, we’ll look at how to add a delay onMouseOver event handler with React.

How to add a delay onMouseOver event handler with React?

To add a delay onMouseOver event handler with React, we can use the Lodash debounce function.

For instance, we write:

import React, { useState } from "react";
import { debounce } from "lodash";

export default function App() {
  const [isHovered, setIsHovered] = useState(false);
  console.log(isHovered);

  const debouncedHandleMouseEnter = debounce(() => setIsHovered(true), 500);

  const handlOnMouseLeave = () => {
    setIsHovered(false);
    debouncedHandleMouseEnter.cancel();
  };

  return (
    <div
      onMouseEnter={debouncedHandleMouseEnter}
      onMouseLeave={handlOnMouseLeave}
    >
      hover me
    </div>
  );
}

We defined the isHovered state with useState.

Then we define the debouncedHandleMouseEnter function by passing in the event handler function into Lodash’s debounce function.

We set the debounce delay to 500ms.

Next, we have the handlOnMouseLeave function where we call debouncedHandleMouseEnter.cancel to cancel the calling of the debouncedHandleMouseEnter function when handlOnMouseLeave is called.

Therefore, when we hover over the div, we see isHovered becomes true.

And when we move our mouse away from the div, isHovered becomes false.

Conclusion

To add a delay onMouseOver event handler with React, we can use the Lodash debounce function.

Categories
React Answers React Native

How to create a weather app with React Native?

(Source code is at https://github.com/jauyeunggithub/rook-hotel-answers/blob/master/q5.txt)

Sometimes, we want to create a weather app with React Native.

In this article, we’ll look at how to create a weather app with React Native.

How to create a weather app with React Native?

To create a weather app with React Native, we can make requests to a weather API to get weather data when someone enters a query in the search box.

For instance, we write:

import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';

// You can import from local files
import { useState, useEffect } from 'react';
import { Card } from 'react-native-paper';
import { TextInput, Button } from "react-native";


export default function App() {
  const [data, setData] = useState({});
  const [query, setQuery] = useState('');

  const getWeather = async () => {
    const res = await fetch(`https://www.metaweather.com/api/location/search/?query=${query}`);
    const [{woeid}] = await res.json();
    const resWeather = await fetch(`https://www.metaweather.com/api/location/${woeid}`);
    const d = await resWeather.json();
    setData(d);
  };

  return (
    <View style={styles.container}>
      <TextInput value={query} onChange={e => setQuery(e.target.value)} placeholder='Type Location to Search' />
      <Button title='Search' onPress={getWeather} />      
      <Card>
        {JSON.stringify(data)}
      </Card>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
});

We define the data state to store the weather data.

And we have the query state to store the query input value.

Next, we define the getWeather function to make GET requests to the MetaWeather API with fetch.

And we call setData to set data to the result of the 2nd request.

Then we render a Virew with a TextInput to let users enter a query to search for weather data.

We have a Button which calls getWeather to make requests for the weather data according to the query value.

Then we display the retrieved data in a Card.

We add some styles to the View to center the content with justifyContent set to center and set a backgroundColor.

Conclusion

To create a weather app with React Native, we can make requests to a weather API to get weather data when someone enters a query in the search box.

Categories
React Answers

How to render a HTML comment in React?

Sometimes, we want to render a HTML comment in React.

In this article, we’ll look at how to render a HTML comment in React

How to render a HTML comment in React?

To render a HTML comment in React, we can use the dangerouslySetInnerHTML prop.

For instance, we write:

import React from "react";

const ReactComment = ({ text }) => {
  return <div dangerouslySetInnerHTML={{ __html: `<!-- ${text} -->` }} />;
};

export default function App() {
  return <ReactComment text={"My beautiful HTML comment"} />;
}

We set dangerouslySetInnerHTML to an object that has the __html property set to a string with the HTML comment.

Then we should see the comment when we inspect the HTML code in the Elements tab of the dev console of our browser.

Conclusion

To render a HTML comment in React, we can use the dangerouslySetInnerHTML prop.

Categories
React Answers

How to Map the Children of a Parent Component in React?

Sometimes, we want to map the children of a parent component in React.

In this article, we’ll look at how to map the children of a parent component in React.

Map the Children of a Parent Component in React

To map the children of a parent component in React, we can use the React.Children.map method.

For instance, we write:

import React from "react";

const Wrapper = ({ children }) => (
  <div style={{ color: "red" }}>{children}</div>
);

const OpaqueWrapper = ({ children }) =>
  Array.isArray(children) ? (
    <Wrapper>
      {React.Children.map(children, (child) =>
        React.cloneElement(child, {
          style: { ...child.props.style, opacity: 0.5 }
        })
      )}
    </Wrapper>
  ) : null;

export default function App() {
  return (
    <div>
      <OpaqueWrapper>
        <p style={{ fontWeight: "bold" }}>foo</p>
        <p>bar</p>
        <p>baz</p>
      </OpaqueWrapper>
    </div>
  );
}

We have the Wrapper that takes the children components and wrap them in a div.

And we set the color of the content to red.

Then we have the OpaqueWrapper that takes the children prop and calls the React.Children.map with children and a callback to return the components that we cloned with React.cloneElement.

During the processing of cloning, we set the style prop to merge the style prop in the original child component and combine it with opacity set to 0.5 with the spread operator.

Now we should see foo being red, bold and translucent and the rest of the text are red and translucent.

Conclusion

To map the children of a parent component in React, we can use the React.Children.map method.

Categories
React Answers

How to Format a Date Inside a React component?

Sometimes, we want to format a date inside a React component.

In this article, we’ll look at how to format a date inside a React component.

Format a Date Inside a React component

To format a date inside a React component, we can use the toLocaleDateString method.

For instance, we write:

import React from "react";

const DATE_OPTIONS = {
  weekday: "short",
  year: "numeric",
  month: "short",
  day: "numeric"
};

export default function App() {
  return (
    <div>{new Date(2021, 1, 1).toLocaleDateString("en-US", DATE_OPTIONS)}</div>
  );
}

We have the DATE_OPTIONS object with the weekdayproperty set to‘short’` to show the abbreviation of the day of the week.

year is set to 'numeric' to show the year as a 4 digit number.

month is set to 'short' to show the abbreviation of the month.

And year is set to 'numeric' to show the year as a number.

Then we call toLocaleDateString with the locale string and the DATE_OPTIONS object to return the date string formatted with the specified format options.

As a result, we see:

Mon, Feb 1, 2021

displayed on the screen.

Conclusion

To format a date inside a React component, we can use the toLocaleDateString method.