Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

263
Views
React: How to redirect to new route (different id) from same route?

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

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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>
);
about 4 years ago · Santiago Trujillo Report

0

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;
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!