I'm build custom PrivateRoute for chat app. Here me PrivateRoute:
import { useState, useEffect } from 'react';
import { Route, Navigate } from 'react-router-dom';
import axios from 'axios';
interface PrivateRouteProps {
element: React.ComponentType<any>;
path: string;
}
export function PrivateRoute({ element: Element, path }: PrivateRouteProps) {
const [authenticated, setAuthenticated] = useState(false);
useEffect(() => {
axios
.get('http://golang:8080')
.then((response) => {
if (response.status === 200) {
setAuthenticated(true);
}
})
.catch((error) => {
console.log(error);
});
}, []);
return (
<Route
path={path}
element={
authenticated ? <Element /> : <Navigate to="/login" replace={true} />
}
/>
);
}
How I use it: <PrivateRoute path={RouterPath.ROOT} element={Main} />
When I build my project in console I have these errors: Screen So how to use custom PrivateRoute?
Here is how you can change your private route component, it will only decide to render children or not, no props
import { PropsWithChildren } from 'react'
export function PrivateRoute({ children }: PropsWithChildren) {
const [authenticated, setAuthenticated] = useState(false);
useEffect(() => {
axios
.get('http://golang:8080')
.then((response) => {
if (response.status === 200) {
setAuthenticated(true);
}
})
.catch((error) => {
console.log(error);
});
}, []);
return <>
authenticated ? (
children
) : (
<Navigate to="/login" replace={true} />
)
</>
}
Then use it that way
<Route path={path}>
<Route path={RouterPath.ROOT} element={<PrivateRoute><Main/></PrivateRoute>}/>
</Route>