+ 1

[PublicRoute] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>

PublicRoute.js import { Navigate, Route } from 'react-router'; function PublicRoute({ children, ...routeProps }) { const profile = false; if (profile) { return <Navigate to="/" />; } return <Route {...routeProps}>{children}</Route>; } export default PublicRoute; App.js: import { Routes } from 'react-router'; import SignIn from './pages/SignIn'; import Home from './pages/Home'; import PrivateRoute from './components/PrivateRoute'; import PublicRoute from './components/PublicRoute'; function App() { return ( <Routes> <PublicRoute exact path="/" element={<SignIn />} /> <PrivateRoute exact path="/" element={<Home />} /> </Routes> ); } export default App; Even after getting rid of all errors and warnings, there's still issue with data/component rendering. I've thoroughly explained the problem on Stackoverflow: https://stackoverflow.com/questions/74455230/uncaught-error-publicroute-is-not-a-route-component-all-component-children

14th Nov 2022, 3:00 PM
Asha
Asha - avatar
1 Resposta
+ 1
The issue you’re encountering is because the PublicRoute component is being used as if it were a <Route> component, but it’s not a valid <Route> component. In React Router v6, <Route> and <Routes> have changed compared to previous versions. Changes to React Router v6 <Route> Changes: In React Router v6, <Route> no longer takes children as you’re using it. Instead, it uses the element prop to render components. Wrapper Component: You need to modify the PublicRoute and PrivateRoute components to match the new pattern. Here’s how you can adapt your PublicRoute and App.js for React Router v6: Updated PublicRoute.js In React Router v6, you should use the Outlet component and the useLocation hook for conditional rendering based on authentication or other conditions: jsx Copy code import { Navigate, Outlet, useLocation } from 'react-router-dom'; function PublicRoute({ redirectTo = "/", children }) { const profile = false; // replace with actual profile check const location = useLocation(); if (profile) { // Redirect if user is authenticated return <Navigate to={redirectTo} state={{ from: location }} replace />; } // Render children if not authenticated return <>{children}</>; } export default PublicRoute; Updated App.js In React Router v6, use the element prop for rendering components and PublicRoute as a wrapper around components: jsx Copy code import { Routes, Route } from 'react-router-dom'; import SignIn from './pages/SignIn'; import Home from './pages/Home'; import PrivateRoute from './components/PrivateRoute'; import PublicRoute from './components/PublicRoute'; function App() { return ( <Routes> <Route path="/" element={ <PublicRoute> <SignIn /> </PublicRoute> } /> <Route path="/home" element={ <PrivateRoute> <Home /> </PrivateRoute> } /> </Routes> ); }
5th Sep 2024, 3:35 PM
sudhakar
sudhakar - avatar