Answer the question
In order to leave comments, you need to log in
Component not rendering in react after redirect?
There is such protection of routes
import React from 'react'
import propTypes from 'prop-types'
import { Route, Redirect } from 'react-router-dom'
class ProtectedRoute extends React.PureComponent {
constructor(props) {
super(props)
}
render() {
const {canAccess, component, path, name, exact, strict} = this.props
const routeProps = {
path,
component,
name,
exact,
strict
}
return canAccess ?
<Route { ...routeProps } />
:
<Redirect to="/landing"/>
}
}
ProtectedRoute.propTypes = {
canAccess: propTypes.bool,
component: propTypes.func,
path: propTypes.string,
name: propTypes.string,
exact: propTypes.bool,
strict: propTypes.bool
}
export default ProtectedRoute
import React from 'react'
import { connect } from 'react-redux'
import propTypes from 'prop-types'
import { BrowserRouter as Router, Route } from 'react-router-dom'
import ProtectedRoute from './protectedRoute'
// Pages
import Landing from './pages/Landing'
import Login from './pages/Login'
import Home from './pages/Home'
import Profile from './pages/Profile'
class App extends React.Component {
render() {
const { authenticated } = this.props
return (
<Router>
<div id="app">
<Route path="/login" component={ Login }></Route>
<Route path="/landing" component={ Landing }></Route>
<Route path="/user" component={ Profile }></Route>
<ProtectedRoute exact path="/" component={ Home } canAccess={ authenticated }></ProtectedRoute>
</div>
</Router>
)
}
}
App.propTypes = {
authenticated: propTypes.bool.isRequired
}
function mapStateToProps(state) {
const { authenticated } = state.auth
return {
authenticated
}
}
export default connect(mapStateToProps, {})(App)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question