passing data from one component to another with react router v6

im working on a 2 components weather app project. since the 2 components use a different API but still use the same location query, i want to pass the query from the component 1 to component 2 as the API query. how do i pass the the query since im switching between the components with react router v6 useNavigation in a button. here's the code

    const api = {
        key : "5753c1f304f16ccb493d187a7351c953", 
        base : "https://api.openweathermap.org/data/2.5/"
    }

    const [weather, setWeather] = useState ('')
    const [query, setQuery] = useState ('')

 const search = (e) =>{
        if (e.key === 'Enter') {
        axios.get(`${api.base}weather?q=${query}&units=metric&appid=${api.key}`).then 
        ((response) => {
            console.log(response.data)
            setWeather(response.data)
            setQuery('')
        } )
    }}

const navigate = useNavigate();

return (
    <>
      <div className='App'>
        <div className='search'>
          <input
          type='text'
          className='search-bar'
          value={query}
          onChange={e => setQuery(e.target.value)}
          placeholder='Search Location...'
          onKeyPress={search} />
          <img className='button-icon' src={button} onClick={search}/>
        </div>
            <button className='viewStats' onClick={()=>navigate('/forecast')}>VIEW Forecast</button>

 </>
    
  )
}

export default Home 

1 answer

  • answered 2022-05-04 11:23 Anurag Parmar

    Release of React Router 6 brought huge changes to api.

    You can pass the state from Component 1 to Component 2 like:

    Pass your state from Component 1 as follow:

    navigate('/your-route', { state : { query : ' your-query ' }})
    

    You can recieve state in Component 2 as follow:

    const { state } = useLocation();
    const { query } = state;
    

    Above solution works for only React Router v6.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum