I found this (reacttraining.com) site, which explains react-router with some examples. But I am not be able to do this with a typescript class. What I want to do is extend the Route class to build my own one. Right now I want to implement it in typescript for authentication as in the following example from the site.
const PrivateRoute = ({ component, ...rest }) => (
<Route {...rest} render={props => (
fakeAuth.isAuthenticated ? (
React.createElement(component, props)
) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}/>
)
)}/>
)
I searched a lot, but couldn't find a site that explains the function to implement and which typed properties to call to nested routes. An ES6 class will be also helpful, thank you.
function App() { return ( <BrowserRouter> <Routes> <Route path="/" element={<Public />} /> <Route path="/private" element={<Private />} /> </Routes> </BrowserRouter> ); } const Public = () => <div>public</div>; const Private = () => <div>private</div>; So as you can see, no more render props or component prop.
Here's my best shot so far, although there's still one any
remaining :)
import * as React from "react"
import {Redirect, Route, RouteComponentProps, RouteProps} from "react-router-dom"
type RouteComponent = React.StatelessComponent<RouteComponentProps<{}>> | React.ComponentClass<any>
const AUTHENTICATED = false // TODO: implement authentication logic
export const PrivateRoute: React.StatelessComponent<RouteProps> = ({component, ...rest}) => {
const renderFn = (Component?: RouteComponent) => (props: RouteProps) => {
if (!Component) {
return null
}
if (AUTHENTICATED) {
return <Component {...props} />
}
const redirectProps = {
to: {
pathname: "/auth/sign-in",
state: {from: props.location},
},
}
return <Redirect {...redirectProps} />
}
return <Route {...rest} render={renderFn(component)} />
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With