How to build a weather app in React Js | React js weather app.

weather-app in react js
weather-app in react js

Hi, welcome here In this tutorial, we will build a weather app using react js. This is the complete tutorial on how to develop a react js weather app. The prerequisites for this project are as follows:

  • Node.js should be installed in your system.
  • Create a brand new ReactJs project. Just copy the code below:
				
					code to create reactjs project:

npx create-react-app my-app
				
			

The brand-new React Js project should look like this:

brand new react js app
brand new react js app

Here is your code for the App.js file, copy the code below and paste it into your App.js file:

				
					import logo from './logo.svg';
import './App.css';
import { useState } from 'react';
import axios from 'axios';

function App() {
  const [query, setQuery] = useState()
  const [weather, setWeather] = useState({
    loading: false,
    data: {},
    error: false,
  });

  const toDate = () => {
    const months = [
      'January',
      'February',
      'March',
      'April',
      'May',
      'June',
      'July',
      'August',
      'September',
      'October',
      'Nocvember',
      'December',
    ];
    const days = [
      'Sunday',
      'Monday',
      'Tuesday',
      'Wednesday',
      'Thursday',
      'Friday',
      'Saturday',
    ];

    const currentDate = new Date();
    const date = `${days[currentDate.getDay()]} ${currentDate.getDate()} ${months[currentDate.getMonth()]}`
    return date;

  }

  const search = async (event) => {
    if (event.key === 'Enter') {
      event.preventDefault();
      setQuery('');
      setWeather({ ...weather, loading: true });
      const url = 'https://api.openweathermap.org/data/2.5/weather?';
      const appid = '316327ce14e6cbd09464551460371b90';

      await axios
        .get(url
          , {
            params: {
              q: query,
              units: 'metric',
              appid: appid,
            },
          }
        )
        .then((res) => {
          console.log('res', res);
          setWeather({ data: res.data, loading: false, error: false });
        })
        .catch((error) => {
          setWeather({ ...weather, data: {}, error: true });
          setQuery('');
          console.log('error', error);
        });
    }
  };

  return (
    <div className="App">
      <h1>
        Weather App with React Js  <span>
          ☁
        </span>
      </h1>
      <div className='search-bar'>
        <input
          type="text"
          className='city-search'
          placeholder='Search city'
          name="query"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          onKeyPress={search}
        />
      </div>

      {
        weather.loading && (
          <>
          <br></br>
          <br></br>
          <h4>Loading...</h4>
          </>
        )
      }
      {
        weather.error && (
          <>
          <br></br>
          <br></br>
          <span className='error-message'>
            {/* <span style={{ 'font'}}> */}
              ❌ Sorry city not found, please try again.
            {/* </span> */}
          </span>
          </>
        )
      }

      {
        weather && weather.data && weather.data.main && (
          <div>
            <div className='city-name'>
              <h2>
                {weather.data.name}, <span>{weather.data.sys.country}</span>
              </h2>
            </div>
            <div className='date'>
              <span>{toDate()}</span>
            </div>
            <div className='icon-temp'>
              <img 
              src={`https://openweathermap.org/img/wn/${weather.data.weather[0].icon}@2x.png`}
              alt={weather.data.weather[0].description}
              />
              {Math.round(weather.data.main.temp)}
              <sup className='deg'>°C</sup>
            </div>
            <div className='des-wind'>
              <p>{weather.data.weather[0].description.toUpperCase()}</p>
              <p>Wind speed: {weather.data.wind.speed}m/s</p>
            </div>
          </div>
        )
      }

    </div>
  );
}

export default App;

				
			

Here is your code for the App.css file, copy the code below and paste it into your App.css file:

				
					html {
  background-color: #e0e0e0;

}

.app-name {
  font-size: 2.3rem;
}


.App {
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 1440px;
  height: 90vh;
  text-align: center;
  margin: 35px auto;
  border-radius: 50px;
  background: linear-gradient(145deg, #cacaca, #f0f0f0);
  box-shadow: 20px 20px 60px #bebebe,
    -20px -20px 60px #ffffff;
}

.city-search {
  width: 200px;
  box-sizing: border-box;
  border: 2px solid #ccc;
  outline: none;
  border-radius: 20px;
  font-size: 16px;
  background-color: rgb(243, 243, 243);
  background-position: 10px 10px;
  background-repeat: no-repeat;
  padding: 12px 20px 12px 40px;
  -webkit-transition: width 0.4s ease-in-out;
  transition: width 0.4s ease-in-out;
}

.city-search:focus {
  width: 60%;
}

.city-name {
  font-size: 1.25em;
}

h2 {
  margin-bottom: 10px;
}

.date {
  font-size: 1.25em;
  font-weight: 500;
}

.icon-temp {
  font-size: 4rem;
  font-weight: 700;
  color: #1e2432;
  text-align: center;
}

.deg {
  font-size: 2rem;
}

.des-wind {
  font-weight: 500;
}

.error-message {
  display: block;
  text-align: center;
  color: rgb(204, 13, 13);
  font-size: 30px;
  font-weight: bold;
  margin-top: auto;
}
				
			

After writing the code into the files (don’t forget to save it ,) you can run the command below:

				
					npm run start