I'm using react-router to set up my application, and try to use <Redirect/>
to set router for authentication.
Route
component have two different components, one is private Route
, another is public route
.
Expect result : when auth is false, the page should jump back to a public page, which I set <Redirect to={"/public"} />
so far it seems route works fine, but redirect doesn't work properly.
Any ideas are welcome! Thanks!!
PrivateRoute
interface PrivateRouteProps {
isLogin: boolean;
privateRoutes: RouteItem[];
}
const PrivateRoute: React.FunctionComponent<PrivateRouteProps> = (
props: PrivateRouteProps
) => {
return (
<>
{props.isLogin ? (
props.privateRoutes.map(item => {
return <Route key={item.path} {...item} />;
})
) : (
<Redirect to={PUBLIC.path} />
)}
</>
);
};
PublicRoute
interface PublicProps {
publicRoutes: RouteItem[];
}
const PublicRoute: React.FC<PublicProps> = (props: PublicProps) => {
return (
<>
{props.publicRoutes.map(route => (
<Route key={route.path} {...route} />
))}
</>
);
};
Route
<BrowserRouter>
<Switch>
<PublicRoute publicRoutes={publicRoutes} />
<PrivateRoute privateRoutes={privateRoutes} isLogin={login} />
</Switch>
</BrowserRouter>
UPDATE
As the accepted answer mentioned, it's all about <Switch/>
works with Fragment, so I modified my routes as following, it works like a charm.
Just update it for someone may have similar question.
<BrowserRouter>
<Switch>
{publicRoutes.map(item => {
return <Route key={item.path} {...item}/>
})}
{privateRoutes.map(item => {
return <PrivateRoute key={item.path}
exact={item.exact}
component={item.component}
path={item.path}
redirectPath={SIGN_IN.path}
/>
})}
</Switch>
</BrowserRouter>