Home > Software engineering >  How can I pass parameters to route with navigate function in react?
How can I pass parameters to route with navigate function in react?

Time:04-27

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

CodePudding user response:

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
  • Related