skip to Main Content
import React, { useContext } from "react";
import { AuthContext } from "../context/auth";
import { Navigate, useLocation } from "react-router-dom";

const PrivateRoute = ({ component }) => {
  const { user } = useContext(AuthContext);
  let location = useLocation()
  if (!user) {
    return <Navigate to='/login' state={{ from: location }} />
  };

  return (component);
};

export const PublicRoute = ({ component }) => {
  const { user } = useContext(AuthContext);
  if (!user) {
    return (component);
  };
  return <Navigate to='/dashboard' />
};

export default PrivateRoute;
<Routes>
  <Route exact path="/" element={<Home />} />
  <Route path="/about" element={<About />} />
  <Route
    path='/register'
    element={<PublicRoute><Register /></PublicRoute>}
  />
  <Route
    exact
    path='/login'
    element={<PublicRoute><Login /></PublicRoute>}
  />
  <Route
    exact
    path='/dashboard'
    element={<PrivateRoute><Dashboard /></PrivateRoute>}
  />
</Routes>

I tried to prevent users who are already logged in from accessing the register or login page and it worked but now after logging out I am not able to access login and register pages.

2

Answers


  1. Chosen as BEST ANSWER

    I was just trying random stuff and it started working i would still like an explanation if possible.

    these were the changes i made

    export const PublicRoute = ({Component: component}) => {
      const { user } = useContext(AuthContext);
      if (user) {
        return <Navigate to='/dashboard' />
      };
    
      return (component );
    };
    
    
          <Routes>
            <Route exact path="/" element={<Home/>} />
            <Route path="/about" element={<About/>} />
            <Route path='/register' element={<PublicRoute  Component={<Register/>}/>}/>
            <Route exact path='/login' element={<PublicRoute  Component={<Login/>}/>}/>
            <Route exact path='/dashboard' element={<PrivateRoute Component={<Dashboard/>}/>}/>
          </Routes>
    

  2. The route guards aren’t passed any component prop. You likely meant to use the implicit children prop.

    const PrivateRoute = ({ children }) => {
      const { user } = useContext(AuthContext);
      let location = useLocation()
      if (!user) {
        return <Navigate to='/login' state={{ from: location }} />
      };
    
      return children;
    };
    
    export const PublicRoute = ({ children }) => {
      const { user } = useContext(AuthContext);
      if (!user) {
        return children;
      };
      return <Navigate to='/dashboard' />
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search