React Router v5 + TypeScriptで認証(PrivateRoute)
この記事はQiitaの記事をエクスポートしたものです。内容が古くなっている可能性があります。 概要
ついでに認証情報をreduxからHooksで取得するよう変更。
実装
code:PrivateRoute.tsx(tsx)
import React, { Component } from 'react'
import { Route, RouteProps, Redirect } from 'react-router-dom'
import { useSelector } from 'react-redux'
import _ from 'lodash'
import { RootState, AuthState } from './reducers'
const PrivateRoute: React.FC<RouteProps> = props => {
const auth = useSelector<RootState, AuthState>(state => state.auth)
const isAuthenticated = auth.token !== null
return (
<Route
{...rest}
render={innerProps =>
isAuthenticated ? (
<Route {...props} />
) : (
<Redirect
to={{
pathname: '/login',
state: { from: innerProps.location }
}}
/>
)
}
/>
)
}
export default PrivateRoute