Search code examples
javascriptreactjsreact-router-dom

<ProtectedRoute /> is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>


Hello to All Devs visiting StackOverflow I have a Problem working with my Protected Route it gives me the error of [ProtectedRoute] is not a component. All component children of must be a or <React.Fragment> at


const adminUsers = [
{username:'admin', password:'admin'}
 ...etc
]
const ProtectedRoute = ({ element, ...rest }) => {
  const isAuthenticated = localStorage.getItem('user');
  const isAdmin = adminUsers.some(user => user.username === isAuthenticated);

  const renderFunction = (props) => {
    if (isAuthenticated && isAdmin) {
      return element; // Render the protected route element
    } else {
      return <Navigate to="/login" replace state={{ from: props.location }} />; // Redirect with location state
    }
  };

  return <Route {...rest} render={renderFunction} />;
};

export default ProtectedRoute;


import { BrowserRouter, Link, Route, Routes, Router } from 'react-router-dom';
import Home from './pages/Home';
import Login from './pages/Login';
import Register from './pages/Register';
import BookingCar from './pages/BookingCar';
import AddCar from './pages/AddCar';
import Admin from './pages/Admin';
import EditCar from './pages/EditCar';
import ProtectedRoute from './components/ProtectedRoute';
import UserBookings from './pages/userBookings';

function App() {
  return (
    <BrowserRouter>
      <Routes>
    
        <Route path="/" element={<Home />} />
        <Route path="/login" element={<Login />} />
        <Route path="/register" element={<Register />} />
        <ProtectedRoute path="/booking/:carid" element={<BookingCar />} />
        <ProtectedRoute path="/userbookings" element={<UserBookings />} />
        <ProtectedRoute path="/addcar" element={<AddCar />} />
        <ProtectedRoute path="/editcar/:carid" element={<EditCar />} />
        <ProtectedRoute path="/admin" element={<Admin />} />
      </Routes>
    </BrowserRouter>
  );
}

export default App;


I have Tried Multiple way to solve it but gives me this error all the time.


Solution

  • That's the v5 way of doing protected route. With v6 you actually need to use a Route:

            <Route
              path="home"
              element={
                <ProtectedRoute>
                  <Home />
                </ProtectedRoute>
              }
            />
    
    const ProtectedRoute = ({children}) => {
        const canUserAccess = /* some logic *.
        if(!canUserAccess) {
           return <Navigate to={"/login"}/>
        }
    
        return <>{children}</>
    
    }