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

346
Vistas
How to show modals using global state with react-router-dom?

My React app uses react-router-dom for navigation. Within each of the different components for these routes there is the potential need to show some form of Error Modal component when something goes wrong. Instead of needing to import the same Error Modal into every component that needs it, manage state within the parent and declare toggle functions, I would like to do this once outside of all other components and just show the generic Error Modal when needed.

I suspect I may need to use Context API but I haven't used it before.

I found this article but I'm not sure how to implement this with my application that has multiple routes.

Ideally I would like to trigger the modal from my axios interceptor in my index.js and have the modal show on top of whatever page the user is on.

index.js:

    //imports...
    axios.interceptors.response.use(undefined, err => {
      if (err.response.status === 500) {
        // Set show state for error modal here
      }
    
      return Promise.reject(err); 
    });

    ReactDOM.render(<App />, document.getElementById('root'));

App.js:

  import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
  // other imports...

  const App = () => {
    return (    
        <Router>
              <Routes>
                <Route path='/page1' element={<Page1 />}></Route>
                <Route path='/page2' element={<Page2 />}></Route>
              </Routes>
          </Router>     
      );
  };
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I was actually able to solve a similar problem to this using the context API. See below for a brief explanation:

Create your ModalProvider

export const ModalProvider = (props) => {
    const createModal = () => { // ...some modal init code here }
    return (
        <ModalContext.Provider value={{ createModal }}>
            <Modal/>
            {props.children}
        </ModalContext.Provider>
    )
}

You can then wrap your App in this provider and you should have access to the createModal function when accessing context. Hope this helps!

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