Weather applications carry a lot of importance in today’s world, providing various benefits to users everywhere. One of the main benefits is being able to access weather forecasts that help people plan their activities according to future weather conditions beforehand. These apps also help us avoid potentially dangerous weather conditions like hurricanes and tornadoes, allowing us to take preventive action accordingly. Therefore, as programmers, we must know how to build such applications to provide the benefits described above.
Here, we'll be focusing on creating a simple weather app using React. Before starting, let's take a look at what the output will be to gain a better idea of the task at hand.
Cities like London, Paris, or Tokyo can be searched in the provided search bar.
The steps to achieve the task of creating this app using React are outlined below.
If we don't have a React app already set up on our systems, we can create one by executing the commands, one after the other, as shown below:
npx create-react-app <folder-name>cd <folder-name>
Note: In the place of the
<folder-name>
tag, we can write a directory name of our choice.
Inside the /src
folder of our React project, we will create a new functional component for our weather app. The component for this purpose is shown below:
import React, { useState } from 'react';// Defining a functional component called Weatherfunction Weather() {// Initialize two pieces of state using the useState hook.// The 'city' variable will hold the name of the city entered by the user.// The 'weatherData' variable will hold the weather data for the selected city.// The 'datanotAvailable' variable will help to display a message in case if a certain city's weather data isn't available// The 'enteredCity' variable stores the entered cityconst [city, setCity] = useState('');const [weatherData, setWeatherData] = useState(null);const [datanotAvailable, setdatanotAvailable] = useState(false);const [enteredCity, setEnteredCity] = useState('');// Defining a function called getWeatherDataconst getWeatherData = () => {// Simulating weather data for different citiesconst weatherInfo = {London: { temperature: '18°C', description: 'Cloudy' },Paris: { temperature: '22°C', description: 'Sunny' },Tokyo: { temperature: '26°C', description: 'Rainy' },};// Retrieving weather data for the city entered by the userconst data = weatherInfo[city];if (data) {// If data exists for the entered city, set the weatherData state with this data// setdatanotAvailable is set to falsesetWeatherData(data);setdatanotAvailable(false);setEnteredCity(city); // Update enteredCity with the entered city} else {// If no data exists for the entered city, set weatherData to null// setdatanotAvailable is set to truesetWeatherData(null);setdatanotAvailable(true);setEnteredCity(''); // Clear enteredCity when there's no data available}};// Return the UI for the Weather component using a render methodreturn (<div><h1>A simple weather app in React</h1><inputtype="text"placeholder="Enter city"value={city}// Attach an event handler to the input field that updates the 'city' state when the user typesonChange={(e) => setCity(e.target.value)}/><button onClick={getWeatherData}>Get Weather</button>{/* Render weather data if it exists, else a message showing that the weather data is not found */}{weatherData && (<div><h2>Weather in {enteredCity}</h2><p>Temperature: {weatherData.temperature}</p><p>Weather: {weatherData.description}</p></div>)}{datanotAvailable && <p>City not found! Try entering again</p>}</div>);}// Export the Weather component as the default export of this moduleexport default Weather;
Here, a React component called Weather
allows us to enter a city name which is available inside the weatherInfo
variable containing simulated weather data and retrieves that data for the entered city name. After this, when we click the "Get Weather" button, the temperature and weather description for that city will be displayed on the webpage.
Note: To add more weather data for various cities, we can add them inside the
weatherInfo
variable.
Next, we will make sure that the weather component made in the previous step is present in our App.js
file. This can be done using the code shown below:
import React from 'react';import './App.css';import Weather from './Weather';function App() {return (<div className="App"><Weather /></div>);}export default App;
Finally, we will run the React app using the npm start
command.
After following all the steps above, we can see the weather app below in its working state. Run it to see it in action:
import React from 'react'; import './App.css'; import Weather from './Weather'; function App() { return ( <div className="App"> <Weather /> </div> ); } export default App;
In conclusion, this simple weather app serves as a foundational example of how to build interactive and reactive user interfaces using React. When dealing with real-life problems, we can replace the simulated weather data used above with an actual API call to fetch from a service like OpenWeatherMap.
Free Resources