Redirect with React Router v6
jkap100
Posted on May 4, 2022
Issue
Building an app that will redirect a user back to the login page if not authenticated.
Solution
We can use Navigate with react router 6 and some simple conditional logic in order to redirect the user back to login when they attempt to view a page and is not authenticated.
Lets assume we have a backend set up that will accept a POST request in order to authenticate a user. Our front end is set up to send a send a POST fetch request and if authenticated store that user in state. The front end fetch could look something like this.
const body = {
username: username,
password: password,
};
fetch("/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(body),
}).then((r) => {
if (r.ok) {
r.json().then((user) => setCurrentUser(user));
navigate("/home");
} else {
r.json().then((err) => setErrors(err.errors));
});
Now we can utilize React Router v6 and Navigate to redirect the the user based on whether or not we have an authenticated user stored in state (currentUser).
Make sure you have installed React Router v6 which can be done with this command :npm install react-router-dom@6.
Next make sure you have imported BrowserRouter, Navigate, Routes, Route from react-router-dom.
import { BrowserRouter, Navigate, Routes, Route } from "react-router-dom"
Once you have your routes set up we can add the following bit of logic to check whether an authenticated user is in state. The following code assumes I have page that shows dogs.
<Route
path="/dogs"
element={
!currentUser ? <Navigate to="/login" /> : <DogsShow />
/>
In english this asking if not currentUser then navigate to /login else render DogsShow.
And there you have it a quick and easy way to add redirect logic to your app.
Posted on May 4, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.