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.
JavaScript
x
10
10
1
import { useNavigate } from 'react-router-dom'
2
3
const exploreTopic = () =>{
4
navigate(`/topic/${props.id}`,{id:props.id});
5
};
6
7
return(
8
<div onClick={exploreTopic}>smth</div>
9
)
10
JavaScript
1
13
13
1
import { useParams } from 'react-router-dom'
2
import './style.css'
3
4
const SingleTopic = ({route,navigate}) => {
5
return (
6
<div>
7
{route.params.id}
8
</div>
9
)
10
}
11
12
export default SingleTopic
13
Advertisement
Answer
You can pass the data this way
JavaScript
1
5
1
const exploreTopic = () =>{
2
navigate(`/topic/${props.id}`,{state:{id:props.id}});
3
};
4
5
And your SingleTopic will become
JavaScript
1
14
14
1
import {useLocation} from 'react-router-dom';
2
3
const SingleTopic = ({route,navigate}) => {
4
const location = useLocation();
5
6
return (
7
<div>
8
{location.state.id}
9
</div>
10
)
11
}
12
13
export default SingleTopic
14