Creating a Weather App with React.js and Weatherbit API

Posted by

Weather App using React.js and Weatherbit API

Weather App using React.js and Weatherbit API

In this article, we will build a simple weather app using React.js and the Weatherbit API. This app will allow users to search for a city and get the current weather information for that city.

Prerequisites

In order to follow along with this tutorial, you will need to have Node.js and npm installed on your system. You will also need to sign up for a free account on the Weatherbit API website to get an API key.

Setting up the project

First, let’s create a new React app using Create React App:

npx create-react-app weather-app

Next, navigate to the project directory and install the Axios library, which we will use to make API calls:

cd weather-app
npm install axios

Creating the Weather component

Now, let’s create a new component called Weather that will handle the logic for fetching weather data from the Weatherbit API. Create a new file called Weather.js in the src/components directory:

        {`import React, { useState } from 'react';
        import axios from 'axios';

        const Weather = () => {
            const [city, setCity] = useState('');
            const [weatherData, setWeatherData] = useState(null);

            const handleSearch = async () => {
                const response = await axios.get(`https://api.weatherbit.io/v2.0/current?city=${city}&key=YOUR_API_KEY`);
                setWeatherData(response.data);
            }

            return (
                
setCity(e.target.value)} /> {weatherData && (

{weatherData.data[0].city_name}

Temperature: {weatherData.data[0].temp}°C

Weather: {weatherData.data[0].weather.description}

)}
); } export default Weather;`}

Using the Weather component

Now, let’s import and use the Weather component in the App.js file:

        {`import React from 'react';
        import Weather from './components/Weather';

        function App() {
            return (
                

Weather App

); } export default App;`}

Running the app

Finally, start the development server by running:

npm start

You should now see the Weather App in your browser. Enter a city name in the input field and click the Search button to see the current weather information for that city.

Conclusion

In this article, we have successfully built a Weather App using React.js and the Weatherbit API. You can further improve this app by adding more features like displaying a forecast for the upcoming days or adding a search history functionality. Happy coding!

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@vakilomer
7 months ago

can you share the source code?