Question

You are asked to develop a React App as follow: 1) Create a new component, name...

You are asked to develop a React App as follow:

1) Create a new component, name it YournameComp to the program which extract the Weather info from Weather API (Open Weather Map), and display the current temperature. Upon calling the component, a webform appears which asks user to enter a city name and select the country code (from a drop-down list) and when the user hits the show temperature button, the data will be displayed.

2) Add a Route to your app to navigate to the Weather info when user type localhost:3000/weather.

3) Add the component that you designed in Tuesday class (the form + validation) to the project. Add a new route for this component, so user can navigate through localhost:3000/form

Submit the project (/src + /public) +Take a screenshot of the output.

Homework Answers

Answer #1

It is not possible to post everything inside the react app therefore I am posting only the needed files and specifying its file name and location step by step:

1. Open cmd and Create the react app using "npx create-react-app weather" . (Assuming weather is your app name)

2. Open the newly created weather folder

3. Remove node modules folder

4. Open package.json, erase everything and paste this :

{
  "name": "weather",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "axios": "^0.20.0",
    "react": "^16.14.0",
    "react-dom": "^16.14.0",
    "react-router-dom": "^5.2.0",
    "react-scripts": "3.4.3",
    "react-select": "^3.1.0",
    "react-select-country-list": "^2.2.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

5. Now open cmd in the same folder "weather" and enter command "npm install"

6. AFter that Remove everything in the src folder of weather

7.Inside src folder create a file named "index.js" and paste :

import React from 'react';
import ReactDOM from 'react-dom';

import App from './App';
//Importing the App component and rendering in #root
ReactDOM.render(<App/>,document.querySelector('#root'));

8. Create a file named "App.js" and paste:

import React, { Component } from 'react';
import {BrowserRouter,Route,Switch} from 'react-router-dom';
import Weather from './components/Weather';
import Home from './components/Home';

export default class App extends Component {
    render() {
        return (
            //Switch component is used so that multiple render of screen does not happen in same time
            //Using Switch only one component renders at a time
            //I made the Home Component to render something in the root path "/"
            <BrowserRouter>
                <Switch>
                    <Route path="/" exact component={Home}/>
                    <Route path="/weather" component={Weather}/>
                </Switch>
            </BrowserRouter>
        )
    }
}

9. Create a file named "apiKey.js" and paste this :

//We store the apikey in this file and export it to required files when needed
const apiKey='2df1eb06362412d37e66f64e1378e28a';

export {apiKey};

10. Create a folder named "components" inside the src folder and inside components folder create 2 files named "Home.js" and "Weather.js".

11. In Home.js paste this :

import React, { Component } from 'react';
import {Link} from 'react-router-dom';

export default class Home extends Component {
    render() {
        return (
            <div>
                <Link to="/weather">Go To Weather page</Link>
            </div>
        )
    }
}

12. In Weather.js paste this :

//I used a library called "react-select-country-list" to get the list of country codes and another library "react-select" to render the codes in a select tag
import React, { Component } from 'react'
import countryList from 'react-select-country-list';
import Select from 'react-select';
import axios from 'axios';
import {apiKey} from '../apikey';

export default class Weather extends Component {
    constructor(){
        super();
        this.state={
            temperature:null,
            city:null,
            countryCode:null,
            options:null
        }
    }
    componentDidMount(){
        let res=countryList().getData();//We get the list of country and country codes
        let options=[];
        //The response from countryList().getData() actually contains array of objects {label:countryname,value:countrycode}
        //So i changed it to {label:country,value:countrycode} by looping into the array and pushing the new object to a new array options
        res.forEach(data=>{
            let temp={
                value:data.value,
                label:data.value
            }
            options.push(temp)
        })
        this.setState({options})
    }
    getTemperature=async (e,city,countryCode)=>{
        e.preventDefault();
        //API call to fetch the temperature using city and countrycode
        const data=(await axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${city},${countryCode}&appid=${apiKey}`)).data;
        const temperature=data.main.temp;
        this.setState({temperature:temperature-273.15})
    }
    render() {
        const {temperature,city,countryCode,options}=this.state;
        if(options===null){
            return <div>Loading...</div>
        }
        return (
            <div style={{display:"flex",alignItems:"center",justifyContent:"center"}}>
                <form style={{width:"600px"}}>
                    <label>City Name</label><br/>
                    <input type="text" name="city" onChange={e=>{this.setState({city:e.target.value})}}/><br/>
                    <label>Country Code</label>
                    <Select
                        options={options}
                        value={countryCode}
                        onChange={value=>{this.setState({countryCode:value})}}
                    />
                    <button onClick={(e)=>{this.getTemperature(e,city,countryCode.value)}}>Show Temperature</button>
                    {temperature?<div>Temperature : {temperature}*C</div>:null}
                </form>
            </div>
        )
    }
}

13. YOu are all set now in cmd type "npm start" to run the project

If you have any issue or doubt with anything feel free to comment out.

Have a nice day

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT