DEV Community

Cover image for Weather widget / component in Next.js
skidee
skidee

Posted on

Weather widget / component in Next.js

Dynamic Weather Widget

Follow these steps to integrate a dynamic weather widget into your Next.js project.

Step 1: Create an API Route

  1. Inside your app folder, create a new folder named api.
  2. Inside the api folder, create a subfolder for your weather route (e.g., weather).
  3. Add a file named route.js inside the weather folder.

You can find the code for route.js here.

Make sure to change the name of the city in the code as needed:

City Name Change

Step 2: Add the Environment Variable

  1. Go to the OpenWeatherMap website, create an account, and navigate to the My API keys section in your profile to generate an API key.

It might take a few minutes for the API key to activate and start working.

  1. Create a file named .env in your project folder and add the environment variable with your API key:

Add Environment Variable

If you are hosting the project on Vercel:
Add the environment variable during deployment, or if the project is already deployed, add it through the project dashboard

Step 3: Create a Weather Component

  1. Create a folder named components in your project folder.
  2. Inside the components folder, create a file named Weather.js.
  3. Add the code from here to Weather.js.
  4. Install the dependencies by running the following command in project folder terminal:
   npm install swr framer-motion @fortawesome/react-fontawesome @fortawesome/free-solid-svg-icons @fortawesome/fontawesome-svg-core
Enter fullscreen mode Exit fullscreen mode

Step 4: Import and Use the Weather Component

  1. Import the Weather component in the file where you want to display the widget.
   import Weather from './components/Weather';
Enter fullscreen mode Exit fullscreen mode
  1. Add the Weather component in your JSX:
   <Weather />
Enter fullscreen mode Exit fullscreen mode

Import Weather Component

The weather widget should now be integrated and look similar to this:

It's just straight text, no css around it.

Top comments (0)