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.

Categories
React Answers

How to Toggle Class based on Scroll Position with React?

Sometimes, we want to toggle class based on scroll position with React.

In this article, we’ll look at how to toggle class based on scroll position with React.

Toggle Class based on Scroll Position with React

To toggle class based on scroll position with React, we can listen to the scroll event on the scroll container element.

For instance, we write:

import React, { useEffect, useState } from "react";

export const useScrollHandler = () => {
  const [scroll, setScroll] = useState(1);

  useEffect(() => {
    const onScroll = () => {
      const scrollCheck = window.scrollY > 10;
      setScroll(scrollCheck);
    };

    document.addEventListener("scroll", onScroll);
    return () => {
      document.removeEventListener("scroll", onScroll);
    };
  }, [scroll, setScroll]);

  return scroll;
};

export default function App() {
  const scroll = useScrollHandler();

  return (
    <div style={{ color: scroll ? "red" : "green" }}>
      {Array(200)
        .fill()
        .map((_, i) => (
          <p key={i}>{i}</p>
        ))}
    </div>
  );
}

to define the useScrollHandler hook to watch the scroll event on the document.

We have the scroll state that’s set to true if we scroll more than 10 pixels down the page.

We call setScroll to set the state of scroll in onScroll.

Then we onScroll as the document‘s scroll evnt handler with document.addEventListener.

And we return a function that calls document.removeEventListener to remove the scroll event listener when we unmount the component.

Finally, we return the scroll state so it can be used in other components.

In App, we have some content that we can scroll through.

And we call the useScrollHandler hook to return the scroll state, which is true when we scroll more than 10 pixels down the page and false otherwise.

We set the style prop of to an object with the color property to set the color of the text depending of the value of scroll.

Now we should see green text when we’re at the top of the page and red text when we scroll down.

Conclusion

To toggle class based on scroll position with React, we can listen to the scroll event on the scroll container element.