Is there a way to pass some parameters to a route with the navigate function is react? I found the below approach, but it doesn’t work since the route parameter in the second file is undefined.
import { useNavigate } from 'react-router-dom' const exploreTopic = () =>{ navigate(`/topic/${props.id}`,{id:props.id}); }; return( <div onClick={exploreTopic}>smth</div> )
import { useParams } from 'react-router-dom' import './style.css' const SingleTopic = ({route,navigate}) => { return ( <div> {route.params.id} </div> ) } export default SingleTopic
Advertisement
Answer
You can pass the data this way
const exploreTopic = () =>{ navigate(`/topic/${props.id}`,{state:{id:props.id}}); };
And your SingleTopic will become
import {useLocation} from 'react-router-dom'; const SingleTopic = ({route,navigate}) => { const location = useLocation(); return ( <div> {location.state.id} </div> ) } export default SingleTopic