Setting Up Auth Guards with React Router
Rendering certain routes or pages based on a user’s authentication is important and that’s why I was surprised to see that my googling lead to less than satisfactory results when it comes to authentication guards in React. Sometimes you just need a better understanding (or vocabulary) to harness the powers of the google and React. React router has this example. This is fine. They utilize useAuth. I find it a tad bit hard to follow for a tutorial, however, because it can be even simpler! Here’s how:
state = { auth: false};
Boom. And we’re done! Congrats!
Ok, there’s a bit more.
{ this.state.auth ? <SomeComponent /> : <h1>Please login!</h1> }
You can use a ternary expression in your component’s JSX! So this only renders <SomeComponent /> when this.state.auth is ‘true’. We set auth to true for successful login requests from our server like so:
.then(res => res.json())
.then(json => this.setState({ auth: true }));
This is assuming you throw an error anytime that the login is unsuccessful. That’s really all there is to simple authentication and conditional rendering. When the user is not logged in or logs out, you simply use this.setState({ auth: false }).
Now, there are other ways to do this as well. When using rails, you can set up a before_action in controllers that checks if a user is logged in before any methods are invoked. You can see more here. You would still need error handling on the frontend so this is a bit more work overall. The whole idea of this programming thing is to code as little as possible. If you have other resources, please comment below!
Also, thanks Arya Muali for this wonderful post.