简体   繁体   中英

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>     
      );
  };

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM