hilderic sb hilderic sb -4 years ago 209
Javascript Question

React Router 4 authentification and redirection

I'm trying to implement an authentification system to my app with React Router.
But i'm having trouble to find a correct way to do this.

export default class App extends React.Component {
constructor(props){
super(props);

this.state = {
logged : false
}

}

isUserConnected(){
// Contact server to know if user is connected or not
}

render() {
return (
<Router>
<Switch>
<Route exact path="/" component={Homepage} />
<Route path="/privatePart" component={Application} />
<Route path="/login" component={LoginRedirection} />
<Route component={NotFound} />
</Switch>
</Router>
)
}
}


In the LoginRedirection component, there is a login form that make a POST to connect the user. But how this component can set logged to true in the App component ?

Maybe I should learn redux ? It may be simplier to implement authentification with it ?

Answer Source

Redux could be a solution, but you can do this with React and react-router.

Using react-router, you can use the property onEnter. For example, you can make the privatePart URL accessible only to logged users with something like:

  <Route path="/privatePart" component={Application} onEnter={requireAuth}/> 

requireAuth should be a function that checks if the user has logged in or not. I think that using App's state isn't the best way to do this, since that information will be lost if the web is reloaded. You could store the login token or just a flag in the localStorage when the POST returns OK in the Login component. Then, redirect the user to privatePart and he will only be able to access it if requireAuth returns true (checking the localStorage). It could be something like:

if (localStorage.getItem("logged") === null) {
    return false;
} else {
    return true;
}

where username is the key you would add to the localStorage when the login is successful.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download