In react-router, we cannot push the same route in useHisotry() and cause a re-render. E.g., if component App is showing on route https://localhost:3000 and I click the button Click Me!, it won't cause a re-render:
function App() {
const history = useHistory();
return (
<button onClick={() => {history.push('/')}}> Click Me! </button>
)
}
I want to achieve similar functionality, but I am unsure about the approach or what I am missing.
My current route looks like this: https://localhost:3000/user/1
I want to go to user/2 by clicking a button.
My code looks like the below:
<Route exact path="/user/:userId" component={User} />
function User() {
const history = useHistory();
return (
<button onClick={() => {history.push('/user/2')}}> Click Me! </button>
)
}
The above code changes the route but doesn't re-render the component. How can I fix this issue?
Thanks
My advice is to upgrade to react router dom v6 and use useNavigate , tutorial here
once you import useNavigate from react-router-dom
let navigate = useNavigate();
and on your button you call this function on click passing your desired url
<button onClick={()=> navigate('/users/2')}
Your component's info wont change because you arent rendering anything dynamically in it, so you should grab the userid from the url, and then lets say display it. Check Docs
As the answer below, you can do it exactly as he said.
const { userId } = useParams();
return (
<div>userId: { userId }</div>
);
I don't recommend using history for this case.
If you really need to, inside User component get userId parameter and react on that.
<Route exact path='/user/:userId' component={User} />
const User = () => {
const { userId } = useParams();
return (
<div>userId: { userId }</div>
);
}
export default User;