How can i use Context with react-router-dom v 6.5.0?

Advertisements

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 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?

Thx.

>Solution :

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

Leave a Reply Cancel reply