Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

227
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda