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

Time:12-30

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?

CodePudding user response:

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>

CodePudding user response:

you are trying to use the AuthContext with the RouterProvider but AuthContext have no property or component called RouterProvider.

To use AuthContext in combination with the RouterProvider, you will need to wrap the RouterProvider component in a component that consumes the AuthContext's value (i.e. useContext(AuthContext)).

Here a snippet to help you out... In this we are using AuthContext value to detemine the value of routes and then use it with RouterProvider

const App = () => {
  const auth = useContext(AuthContext);
  const routes = auth.isLoggedIn ? privateRoute : publicRoute;

  return (
    <RouterProvider router={routes} />
  );
};

export default App;

inside and you need to wrap the App component inside AuthContext like ...

ReactDOM.createRoot(document.getElementById("root")).render(
  <React.StrictMode>
    <AuthContext>
      <App />
    </AuthContext>
  </React.StrictMode>
);
  • Related