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

226
Views
Override the back button route with react router replace method on componentWillUnmount

I have a component, which is A and on success of some form filling, i route the user to the B component. Now when the user clicks on back button of browser, instead of going back to A component, i re route him to the Home Page

App.js

<Route exact path="/">
   <Root />
 </Route>
 <Route path="/home">
   <Home />
 </Route>
 <Route path="/a">
   <A />
 </Route>
 <Route path="/b">
   <B />
 </Route>

A.js

 componentDidMount() {
    console.log("api call");
  }

  handleSubmit = () => {
    // api success
    this.props.history.push({
      pathname: "/b",
      search: "?viewType=success"
    });
  };

B.js

backListener() {
    if (this.props.history.action === "POP") {
      let viewType = new URLSearchParams(this.props.location?.search)?.get(
        "viewType"
      );
      if (viewType === "success") {
        return this.props.history.replace("/home");
      }
      return this.props.history.replace("/");
    }
  }

  componentDidMount() {
    window.addEventListener("popstate", this.backListener);
  }

  componentWillUnmount() {
    this.backListener();
    window.removeEventListener("popstate", this.backListener);
  }

Even though i am pushing the route to /home, but i can see the A.js log of api calling

I don't want to render the A.js from B when the browser back button is clicked.

What am i doing wrong here

Sandbox

Steps:

  1. Click on Go To A
  2. Click on Submit
  3. Click on back button of sandbox
  4. In the console its showing api call (2 times)

How could i override the back button component load when i am pushing the state on componentWillUnmount ?

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