Jose Luiz Junior
Jose Luiz Junior

Reputation: 193

Creating a PrivateRoute in React using Class component

I tried to create a PrivateRoute in react using class component, my code:

app.js

    return (
        <Fragment>
            <Switch>
                <Route exact path="/" component={HomePageContainer} /> 
                <PrivateRoute exact path="/user/:id" component={ProfilePageContainer} />
                <PrivateRoute exact path="/timeline" component={TimelineContainer} />
                <PrivateRoute exact path="/user/:id/edit" component={ProfileEditContainer} />
            </Switch>
        </Fragment>
    );
}

export default App;

PrivateRoute

class PrivateRoute extends React.Component {

    componentDidMount(){
        if(localStorage.jwt){
            this.props.getCurrentUser();
        }
    }

    render() {
        return (
            localStorage.jwt ? 
                (this.props.current_user.id ? 
                    (<Route {...this.props}> </Route> ) : 
                    'Loading...'):
                (<Redirect to={{pathname: "/",state: { from: this.props.location }}}/>)
        );
    }

}

function mapStateToProps(state) {
    return {
        current_user: state.current_user
    }
};

function mapDispatchToProps(dispatch) {
    return bindActionCreators({ getCurrentUser }, dispatch)
}

export default connect(mapStateToProps, mapDispatchToProps)(PrivateRoute)

When my component is inside PrivateRoute it isn't not render but if I use Route works. I think is because I set directly this.props in Route because in another project using function components I set props like a follow snippet:

const PrivateRoute = ({component: Component, ...rest}) =>(
    <Route {...rest} render={props => (
        localStorage.getItem('user') ? <Component {...props} /> : <Redirect to={{pathname: '/login'}} />
    )} />
)

I could using function components in this project, but I want to learn using class components in react. How can I use spread operator like I use in a example t o fix my PrivateRoute in my project? Thank you :)

Upvotes: 0

Views: 224

Answers (1)

Tam Nguyen
Tam Nguyen

Reputation: 181

render() {
    const {component: Component, ...rest} = this.props;
    return (
      <Route {...rest} render={props => (
        localStorage.getItem('user') ? <Component {...props} /> : <Redirect to={{pathname: '/login'}} />
    )} />
        )
        );
    }

You can achieve this easily with class component. Another thing is that your logic about check user logged in should be centralized, you shouldn't check both localStorage and redux

Upvotes: 1

Related Questions