Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create own react route class in typescript

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.

like image 431
CordlessWool Avatar asked Feb 18 '17 00:02

CordlessWool


People also ask

How do I create a private route in react typescript?

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.


1 Answers

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)} />
}
like image 184
Jacka Avatar answered Sep 23 '22 09:09

Jacka