My application in total has 5 routes, out of these 5 for four of them I need a condition to be true first to let user access those routes. So I wanted to create checks for said routes. I made PublicRoute and PrivateRoute Components
import { Route } from 'react-router-dom';
const PublicRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={(props) => <Component {...props} />} />
);
export default PublicRoute
import { Route, Redirect } from 'react-router-dom';
const PrivateRoute = ({ component: Component, isAuthenticated, ...rest }) => (
<Route
{...rest}
render={(props) =>
isAuthenticated ? (
<Component {...props} />
) : (
<Redirect to="/" />
)
}
/>
);
export default PrivateRoute
And my app.js
import { Routes } from "react-router-dom"
import PublicRoute from "./components/PublicRoute"
const App = () => {
return (
<>
<Routes>
<PublicRoute
exact
path="/"
component={Com}
/>
</Routes>
</>
)
}
export default App
const Com=()=>(
<>
<h1>Hi</h1>
</>
)
And currently I am getting this error
not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>
at invariant (history.ts:48
Given I am returning a Route Component I can't quite understand why this error pops up. Eventually I want a way to perform checks and keep code clean, If there's another efficient way please let me know!
The Routes component needs a literal Route component as the child.
This worked for me -
PublicRoute
import { Route } from "react-router-dom";
const PublicRoute = ({ component: Component, ...rest }) => (
<Component {...rest} />
);
export default PublicRoute;
App.js
import { BrowserRouter, Routes, Route } from "react-router-dom";
import PublicRoute from "./PublicRoute";
const App = () => {
return (
<BrowserRouter>
<Routes>
<Route
exact
path="/"
element={
<PublicRoute component={Com} msg={"there"} person={"sandy"} />
}
/>
</Routes>
</BrowserRouter>
);
};
export default App;
const Com = ({ msg, person }) => (
<>
<h1>
Hi {msg} {person}
</h1>
</>
);