Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

};

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading