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

330
Views
How to use the browser back button to close a Modal in react-router v6

I have a simple modal that displays a larger version of a picture when a React component clicks a thumbnail. I would like the modal to close when the back button is pressed in the browser instead of the default behavior. I have seen this question answered using browserHistory(), but that has been replaced with useNavigate() in v6, and I am not sure how to implement this.

Edit: I implemented the below answer, but I had to nest the route from the modal within the parent compnenet's route and then add an in the parent component. If you simply make two seperate routes it will unmount the parent component when the modal compontent mounts.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Yes you can... here's one (of the many) approach that you can take. First thing first, you have to use url to determine if modal is open or not.

For example

  • /photos show photo list page
  • /photos/:id show photo's detail modal

And you can do something like this

<Routes>
  <Route path="/photos" element={<PhotoList />} />
  <Route path="/photos/:id" element={<PhotoDetailModal />} />
</Routes>

Notice that I didn't put "exact" in /photos Route, because I expect the photos page to still show underneath the modal.

And in photo list page, you can open a modal by just change the url

// Your Photo's list

<Link to={`/photos/${photo.id}`}>
  <img src="your photo" />
</Link>

Now the browser history will work as your friend, and the back button will close modal (since it changes url from /photos/1 to /photos

about 4 years ago · Juan Pablo Isaza 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!