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

147
Views
Close a modal when user clicks back button in browser React Js

I am showing user a modal that takes over the entire screen if user is accessing the website on phone. A user tends to instinctively click the back button on their phone to go back to the previous screen instead of using the close button provided on the modal.

Is there a way to intercept the function that is triggered when a user clicks the back button? I want to close the modal when user clicks the back button on their phone, instead of having them redirect to the previous page.

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

0

Use the History API. An example on how to acomplish this is:

//listen for state changes
window.onpopstate = (event) => 
{
   if (!event.state.modalOpened)
   {
     closeModal()
   }
}

//change the actual page state so it contains the modalOpened property
window.history.replaceState({modalOpened: false})

function openModal(content) 
{
    //push new state, put the modal information in the state object, this will push a new state, when the user presses the back button, the browser will just trigger the onpopstate event, instead of going to the previous page
    window.history.replaceState({modalOpened: true})

    //this is any code you use to open your modal, for example
    ReactDOM.render(<Modal>{content}</Modal>, document.getElementById("moda-container")
}
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!