Home > front end >  React: How to redirect to new route (different id) from same route?
React: How to redirect to new route (different id) from same route?

Time:12-25

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

CodePudding user response:

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')}

CodePudding user response:

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