A simple weather application in ReactJs that allows users to search for weather information by entering the name of a city. The app fetches weather data from the OpenWeatherMap API and displays the temperature, description of weather conditions, feels-like temperature, and humidity for the specified city. Here's how you can setup you app similar to this:
-
Dependencies and Imports:
- Import the necessary dependencies and styles at the beginning of
App.jsfile, including Axios for making API requests and React libraries for managing state and rendering the UI.
- Import the necessary dependencies and styles at the beginning of
-
State Setup:
- Use the
useStatehook to create two state variables:weatherData: This state variable will store the weather data for the selected city once it's fetched from the API.city: This state variable is used to store the city name entered by the user in the search input.
- Use the
-
Fetching Weather Data:
-
Define an
useEffecthook that triggers whenever thecitystate changes. Inside this effect, create an asynchronous function calledfetchWeatherData. -
fetchWeatherDatamakes an API request to OpenWeatherMap using Axios. It constructs the URL with the API key and the user's input city name. -
If the request is successful, it sets the fetched weather data into the
weatherDatastate variable. If there is an error, it logs the error to the console.
-
-
Search Input Handling:
- The input field is controlled by the
citystate. When the user types in the input field, thehandleSearchfunction is called, updating thecitystate with the user's input.
- The input field is controlled by the
-
Rendering the Weather Data:
-
The weather data fetched from the API is conditionally displayed in the UI. Check if
weatherDatais not null (i.e., data has been fetched) before rendering the weather information. -
The weather information includes the city name, temperature in Celsius, weather description, feels like temperature, humidity percentage, and wind speed.
-
-
Rendering in index.js:
- In the
index.jsfile, create a React root element usingcreateRootand render yourAppcomponent wrapped inStrictMode.StrictModeis used for highlighting potential problems in the app during development.
- In the