Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
March 23, 2021 09:24 am GMT

Learn React by building a simple weatherapp

Confused about how to learn React? Start building this app

Alt Text

When you begin to learn a technology, start with building small projects so that you will get conceptual and factual knowledge of the technology.

React is an emerging front-end framework that builds your web application conveniently. It helps to build single-page applications that work inside a browser and does not require page reloading during use.

Features of the App

  1. Displays the temperature, region, wind speed, pressure, precipitation and humidity of the device location.
  2. Displays the above-mentioned weather info with a user-specified location in the search bar.

Let's get started

Make sure you have the setup for React with NodeJs and NPM installed in your system.

To create a project run this in your terminal:

npx create-react-app weather_appcd weather_app   npm start

Now we will get to see this screen, where the live update of the app can be viewed on the localhost server.
Alt Text

After this, you will get the required packages for our project. We need not worry about these packages, as we are mainly going to focus on "App.js"."App.js" is the main component in the file which acts as a container to the other components.

We need to remove the default content from the "App.js".

Creating a class

Create a class component and include extendsReact.Component. This will inherit the React component and allow the component to access React.component's function. This component also requires a render method to return the HTML.

Now, we will set the state and assign the input to the state object.

State is an object of a React Component class that can be modified over its lifetime but cannot be accessed from the outside.

class App extends React.Component {  state= {    coords:{      latitude:28,      longitude:77    },  }  render() {    return (      <div className="App">       <div className="container">       </div>      </div>    );  }}

NOTE: Here we are assigning default values to the latitude and longitude if in case the device location is not working.

Getting the weather info of the current location

We will be using componetdidmount() method to assign the device's latitude and longitude. This method is one of the life cycle methods which will be invoked immediately after the component is mounted.

if (navigator.geolocation) {     navigator.geolocation.getCurrentPosition(position => {        let newCoords={          latitude:position.coords.latitude,          longitude:position.coords.longitude        }        this.setState({coords:newCoords});

The current location is obtained and its latitude & longitude is set to the state object.

Next, we will be using a rest API to get the weather details for our application.

Getting API key

To get the API key, you need to Sign In here or you can use any other external API.

We will be using Axios, which is a JavaScript library that makes request access to the rest API. Hence install it in the terminal by npm install axios and import it in the class component.

Now, we will be calling the API by get() method and will be passing the values of latitude & longitude which is set in the state object. After this, we will retrieve our weather data and set it to a new object in the state.

Axios.get(`http://api.weatherstack.com/current?access_key=your_API _key=${this.state.coords.latitude},${this.state.coords.longitude}`).then(res => {          let Weather_data = {          temperature: res.data.current.temperature,          description: res.data.current.weather_descriptions[0],          location: res.data.location.name,          region: res.data.location.region,          country: res.data.location.country,          wind_speed: res.data.current.wind_speed,          pressure: res.data.current.pressure,          precip: res.data.current.precip,          humidity: res.data.current.humidity,          img: res.data.current.weather_icons          }          this.setState({data:Weather_data})      })

Displaying the Weather data

After receiving the data from the API, we will have to display it, so we will be creating a component for displaying the data. After creating the component, you can add the dynamic structure of the application (HTML) and style according to your requirement.

In this component, we will be accessing the data from "App.js", so we need to use props to get the data. Props is a special keyword in React which denotes properties that can pass data from the parent component to the child component unidirectionally.

App.js
  render() {    return (      <div className="App">       <div className="container">        <Navbar changeRegion={this.changeRegion} changeLocation={this.changeLocation}/>        <Display Weather_data={this.state.data}/>       </div>      </div>    );  }
Display.js
import React from 'react'export default function Display(props) {   const { temperature, description, location, region, country, wind_speed, pressure, precip, humidity, img } = props.Weather_data;    return (      <div className="weather-wrapper">        <div className="weather-card">         <div className="header">           <img className="mainImg" src={img} alt="weather-img" />           <h1>{temperature}<sup>o</sup>C , {description}</h1>           <h4>{location}</h4>           <p>{region} , {country}</p>         </div>           <p><b>Wind Speed</b>(km/hr)</p>           <h3>{wind_speed}</h3>           <p><b>Preassure</b>(millibar)</p>           <h3>{pressure}</h3>           <p><b>Precipitation</b>(mm)</p>           <h3>{precip}</h3>           <p><b>Humidity</b>(%)</p>           <h3>{humidity}</h3>          </div>      </div>    )}

Now the weather info will be displayed on the screen. After this, we will be doing a similar procedure to display the weather info of the searched location.

Displaying weather info the searched location

When the user specifies a location in the search box, the value of the searched location will be set to the state object using the Navbar component. Now we can pass the state object with the searched location to the API that retrieves the weather info. This weather info is then displayed using the Display component.

Navbar.js
import React from 'react';import { FaSistrix } from "react-icons/fa";export default function Navbar(props) {    return (        <div className="row">            <div className="col-md-6">                <h1 className="title">Weather App</h1>            <div className="col-md-6">                <form action="" autocomplete="on" className="region" onSubmit={(e) => { props.changeLocation(e) }}>                  <input type="text" className="regioninput" placeholder="Select your region" onChange={(p) => { props.changeRegion(p.target.value) }} />                  <button type="submit" class="searchbutton"><FaSistrix/></button>                </form>            </div>            </div>        </div>    )}
App.js
changeLocation = (e) => {    e.preventDefault();    if(this.state.regionInput){    Axios.get(`http://api.weatherstack.com/current?access_key=your_acess_key&query=${this.state.regionInput}`).then(res => {    if(res.status===200 && res.data.request){      let Weather_data = {        temperature: res.data.current.temperature,        description: res.data.current.weather_descriptions[0],        location: res.data.location.name,        region: res.data.location.region,        country: res.data.location.country,        wind_speed: res.data.current.wind_speed,        pressure: res.data.current.pressure,        precip: res.data.current.precip,        humidity: res.data.current.humidity,        img: res.data.current.weather_icons      }      this.setState({ data: Weather_data });    }
Output of our Web app.

Alt Text

Bravo!!! We have built the app successfully. Hope you have understood the process and concepts of React.

Here is the source code for this project GitHub

Thank you for reading this article. This is my first venture as a writer, I tried my best to make this article understandable and informative. Hope it gets better.Happy coding :) !!

Also, feel free to connect with me LinkedIn if you are facing any issues.


Original Link: https://dev.to/nikitha_janardhanan/learn-react-by-building-a-simple-weather-app-1c44

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To