Home > Back-end >  How to close modal when navigating to another page in React
How to close modal when navigating to another page in React

Time:06-08

I'm using react-router-dom/material UI modal and I want to hide my modal whenever user navigates to another page.

This is my App component,

const App = () => (
  <BrowserRouter>
    <ModalHandlersProvider>
      <Routes>
        <Route path="/" element={<Layout />}>
          <Route index element={<Home />} />
        </Route>
      </Routes>
    </ModalHandlersProvider>
  </BrowserRouter>
);

export default App;

and I'm rendering CustomModal in ModalHandlersProvider component, passing modal related functions using context API.

const ModalHandlersContext = React.createContext(initialState);
export const useModalHandlersContext = () => useContext(ModalHandlersContext);

const ModalHandlersProvider = ({ children }) => {
  const [modal, setModal] = useState(initialState);
  const handlers = {
    openModal: setModal,
    closeModal: () => setModal(initialState),
  };

  return (
    <ModalHandlersContext.Provider value={handlers}>
      {children}
      <CustomModal
        open={modal.open}
        onClose={handlers.closeModal}
        content={modal.content}
      ></CustomModal>
    </ModalHandlersContext.Provider>
  );
};

export default ModalHandlersProvider;

So basically the child components can open/close the modal using handlers from ModalHandlersContext.

I know I could attach a modal closing function(handlers.closeModal) on the element the user clicks, but it's inefficient and also can't cope with users pressing the back button.

I found I can solve it using useRoute() from next.js, but I dont' want to try it now since I'm quite new to React.

Is there any solution to this?

CodePudding user response:

Add useEffect hook in your provider and check if route has changed. Also add close action into ref, to prevent unnecessary call of useEffect.

useEffect(() => {
        if (currentRout !== perRoute) {
         setModal(initialState)
        }
    }, [route])
  • Related