Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close a modal on browser back button using react-router-dom?

I'm using react-router-dom and what I want is to be able to close a Modal when I click browser back button.

Also, in my scenario, the modal component is not the part of Switch. So how can I close the modal.

Thanks in advance. :)

like image 248
Shubham Bisht Avatar asked Jan 18 '20 08:01

Shubham Bisht


People also ask

How can I stop the browser back button using React?

To achieve this, we'll do the following: Create a top-level <Route> in <BrowserRouter> that matches all URLs ( / ) and render App component. Get history object by wrapping App component with withRouter higher-order component. Listen to window object's popstate event and go forward if the user navigates backward.

How do you close a modal on button click React?

To close the modal, simply call the handleClose() function inside the onLoginFormSubmit() function body.

How do you go back in Dom On React router?

To go back to the previous page with React router: Use the useNavigate() hook, e.g. const navigate = useNavigate(); . Call the navigate() function passing it -1 - navigate(-1) . Calling navigate with -1 is the same as hitting the back button.

What is Dom React React Dom router?

React Router DOM is an npm package that enables you to implement dynamic routing in a web app. It allows you to display pages and allow users to navigate them. It is a fully-featured client and server-side routing library for React.


1 Answers

You could probably use something like this to detect the press of the Back button.

componentDidUpdate() {
  window.onpopstate = e => {
    
  }
}

And then, depending on your modal (Bootstrap or something else) you can call .hide() or .close().

like image 152
sotirelisc Avatar answered Oct 18 '22 18:10

sotirelisc