J
J
JuniorJdun2017-08-11 13:36:12
JavaScript
JuniorJdun, 2017-08-11 13:36:12

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

I take the value of canAccess from the redux store, the routing is in App.js actually there and I pass the prop to the component above, the problem is that when a redirect occurs to the component I need, it is not rendered.
Here I found a similar problem https://stackoverflow.com/questions/42782607/redir...
I understand this because of the redax, and in general it feels like the routing is some kind of curve, everything somehow works loosely here it is
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

1 answer(s)
R
Roman Alexandrovich, 2017-08-11
@RomReed

try using just Component instead of PureComponent.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question