Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

351
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda