-3

I'm building a react weather app where users are allowed to enter their city name and the weather info is displayed back to the user.

The problem is, I've got the input and button in a form, and I want to receive data from another component called WeatherApp. I want the user to be able to enter their city and get the weather info using the form.

how do I link the two components

the form component

import '../App.css';
import Input from './Input';
import Button from './Button';
import { useState } from 'react';

const Form = ({handleQueryChange}) => {
    const [city, setCity] = useState('')

    const handleChange = (e) => {
        setCity(e.target.value)
       
    }

    const handleSubmit  = (e) => {
        e.preventDefault();
        handleQueryChange(city);
        
    }
   
    return (  
    <div>
        <form className="inputForm" onSubmit={handleSubmit}>
       <Input value={city} onChange={handleChange} />
       <Button/>
        </form>

    </div>);
}
 
export default Form;

the weatherapp component

import React from 'react';
import { BrowserRouter,  Routes,Route } from 'react-router-dom';
import { useState, useEffect } from 'react';
import { WiDaySunny,WiCloud, WiNightCloudy,WiHumidity, WiNightClear } from 'react-icons/wi';
import Layout from './Layout';
import Home from './Home';
import Minutecast from './Minutecast';
import Hourly from './Hourly';
import Today from './Today';
import '../App.css';


const WeatherApp = () => {
const [data, setData] = useState([]);
const [query, setQuery] = useState('Accra');

const handleQueryChange = (data) => {
    setQuery(data.location.name);

}

const getWeatherIcons = (description) =>{
    switch(description.toLowerCase()) {
        case 'sunny':
            return <WiDaySunny size='100px'/>;
        case 'cloud':
                return <WiCloud  size='100px'/>;
        case 'clear':
                return <WiNightClear size='100px'/>;
        case 'partly cloudy':
            
                return <WiNightCloudy size='150px' color='blue' />;
        default:
                return <WiDaySunny color='red' size='100px' />;

    }
}

const convertToWhole = (tem) =>{
  const whole = Math.trunc(tem);
  return whole;


}

useEffect(()=>{
    
const fetchWeatherData = async () => {
  try {
    const response = await fetch(`https://api.weatherapi.com/v1/forecast.json?key=95f0ddb3a06a4a358cf223933242311&q=${query}&days=10&aqi=yes&alerts=no`);
    const result = await response.json();
    setData(result);

  console.log(result);
  } catch (error) {
    console.error("Error fetching weather data:", error);
  }
 
};
fetchWeatherData();
}, [data]);



    return ( <>
    <div className="formContainer">
    {/* <Form onSubmit={handleQueryChange} /> */}
    </div>
    <BrowserRouter>
    <Routes>
       <Route path ='/'  element={< Layout />}>
       <Route index element={<Home  data={data} getWeatherIcons={getWeatherIcons} convertToWhole={convertToWhole}/>} />
       <Route path='minutecast' element={<Minutecast />}/>
       <Route path='hourly' element={<Hourly data={data} convertToWhole={convertToWhole}/>}/>
       <Route path='today'element={<Today data={data} />}/>
     </Route>
     </Routes>
   </BrowserRouter>
  
    </>
    )
   
}
 
export default WeatherApp;
2
  • You can import your component the same way as you import your Hourly and Today like: import Form from './Form' and use it like <Form/> Commented Jan 14 at 14:39
  • Restructure the components to improve usability. Move the state to a parent component, pass the city, and handleCity as props to the form. Add a button to the form and place the fetch logic inside a function triggered when the button is clicked. The data should be fetched when a user types a city name and clicks the button. Commented Jan 14 at 14:45

1 Answer 1

0

Your question is kinda hard cause you are not giving us enough information. You can use useContext so you can store this information in the context and then use it wherever you can. Or maybe use Local Storage or a Cookie, or maybe create a hook that grabs this info from DB in case you have it.

Would be good to know how you use this form, like is inside an specific page? Is sibling, parent or has no connection with any other component. Maybe you can simply pass this info as a prop (but probably is not the best).

I think this is the only thing I can come up with the info I have from your answer.

In any case I can link you the docs for this stuff:

useContext

passing props

local storage

cookies

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.