Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I pass parameters to route with navigate function in react?

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading