Chris Hughes
Chris Hughes

Reputation: 13

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.

Upvotes: 1

Views: 1701

Answers (1)

Doppio
Doppio

Reputation: 2188

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

Upvotes: 2

Related Questions