Search code examples
javascriptreactjsreact-routerreact-router-domreact-context

How can I use React Context with react-router-dom?


AuthContext:

import { createContext } from "react";
export const AuthContext = createContext(null);

App.js:

const App = () => {
  const isLogin = false;

  if (isLogin) {
    return (
      <RouterProvider router={privateRoute} />
    );
  } else {
    return (
      <RouterProvider router={publicRoute} />
    );
  }
};

export default App;

I try to put <RouterProvider> in AuthContext like this:

<AuthContext.RouterProvider router={privateRoute} />

and like this:

<AuthContext>
  <RouterProvider router={privateRoute} />
</AuthContext>

None of these options worked. What am I doing wrong?


Solution

  • One has nothing to do with the other. The issue is that AuthContext doesn't have any RouterProvider property nor is the code you are trying to use actually using a React context Provider component and value.

    Just wrap the App component with the AuthContext.Provider component and ensure a context value is passed.

    Example:

    <AuthContext.Provider value={{ ..... }}>
      <App />
    </AuthContext.Provider>