How do I useContext hook on React Router v6

Viewed 827

I'm a beginner and I'm currently developing an application using a React Template. The template uses React Router v6 for the router with use Routes() hook. Every route of the application is protected and can be only accessed by logging in

I'm planning to implement login using use Context() hook but I cant seem to figure out how to wrap the routes in the Provider tag.

My two doubts are:

  1. How do I wrap my routes in the <Context Provider> tag
  2. Should I wrap all my routes in an application like this.
1 Answers

First of all you will need the Context. I always prefer to write a hook:

import { createContext, useContext, useState } from "react";

const AuthContext = createContext({
    isAuthenticated: false,
    login: () => {},
    logout: () => {}
});

export function AuthProvider({ children }){

    const [isAuthenticated, setAuthenticated] = useState(false);

    const login = () => {
        setAuthenticated(true);
    }
    const logout = () => {
        setAuthenticated(false);
    }
    return (
        <AuthContext.Provider value={{isAuthenticated: isAuthenticated, login: login, logout: logout}}>
            {children}
        </AuthContext.Provider>
    )
}

export default function AuthConsumer() {
    return useContext(AuthContext); 
}

Then you will need a private route component like this:

import React from 'react';
import { Navigate } from 'react-router-dom';
import useAuth from "./useAuth";

function RequireAuth({ children, redirectTo }) {
    const { isAuthenticated } = useAuth();
    return isAuthenticated ? children : <Navigate to={redirectTo} />;
}

export default RequireAuth;

Finally you will mix in your routes:

import React from 'react';
import { BrowserRouter, Route, Routes, Navigate } from 'react-router-dom';
import Login from './pages/Login';
import RequireAuth from './components/PrivateRoute';
import useAuth from "./components/useAuth";

const Home = () => <div><h1>Welcome home</h1></div>
const Dashboard = () => <h1>Dashboard (Private)</h1>;

function App() {

  const { isAuthenticated } = useAuth();

  return (
    <BrowserRouter>
      <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/dashboard" element={
              <RequireAuth redirectTo="/login">
                <Dashboard />
              </RequireAuth>
            }>
          </Route>
          <Route path="/login" element={<Login />} />
          <Route path='*' element={<Navigate to={isAuthenticated ? '/dashboard' : '/'} />} />
      </Routes>
    </BrowserRouter>
  );
}

export default App;

I hope this will help.

Related