Introduction
If you're a developer working on any modern web application, you're probably aware of how important it is to properly set up routing. When you browse through many React Router tutorials, you may notice that they seldom mention redirects and instead focus on how to use the Link
component. To manage routing in React, we can utilize the react-router-dom package.
In this post, we will look at the many methods and scenarios in which you can utilize redirects in React. We'll also look at some previous strategies and how they functioned with the new replacements for them in React Router v6, which is the most recent version as of the time of this writing.
Prerequisites
In this article, we will use the react-router-dom
package, which we must install in our project. This is accomplished by running one of the following commands in our terminal:
$ npm i react-router-dom
or
$ yarn add react-router-dom
Redirect and Navigate Component
The Redirect
component was usually used in previous versions of the react-router-dom
package to quickly do redirects by simply importing the component from react-router-dom
and then making use of the component by providing the to
prop, passing the page you desire to redirect to.
import { Redirect } from 'react-router-dom';
<Route path='/redirect-page' element={ <Redirect to="/error-page" /> }/>
With the release of React Router v6, the Redirect
component was removed and replaced with the Navigate
component, which operates just as the Redirect
component does by taking in the to
prop to enable you to redirect to the page you specify.
import { Navigate } from 'react-router-dom';
<Route path="/redirect" element={ <Navigate to="/error-page" /> } />
Make sure that you have the route already. For instance, if you would be redirecting to the "/error-page" route, ensure you have already declared the route previously before setting up the redirect. Take note of the order or Route
declarations in the code below:
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import ErrorPage from './ErrorPage';
import Home from './Home';
function App() {
return (
<BrowserRouter>
<Routes>
<Route
path="/"
element={ <Home /> }
/>
{/* The next line is very important for the Navigate component to work */}
<Route
path="/error-page"
element={ <ErrorPage /> }
/>
<Route
path="/redirect"
element={ <Navigate to="/error-page" /> }
/>
</Routes>
</BrowserRouter>
);
}
export default App;
Conditional Redirects
This is something you will likely need to make use of when building web applications. Conditional redirects are simply routing based on certain criteria.
A common scenario might be when you're building an e-commerce platform, and you don't want users to have access to certain components/modals/forms, such as the checkout modal/component, until they've added some products to the cart. If they try to force their way into the page, they should be redirected to the products page so they can first select items.
This is known as conditional redirects. To do this, we would use the useState()
hook to empty the cart array and then apply some criteria to our route.
const [cartItems, setCartItems] = useState([]);
<Route
path="/checkout"
element={ cartItems.length < 1 ? <Navigate to="/products" /> : <Checkout /> }
/>;
In this example, as long as this array is empty, we won't be able to access the /checkout
route until there is at least one item in the cartItems
array.
Replacing the Current URL
In some cases, you might want to replace the current URL in the browser instead of adding (i.e., pushing) it to your browser's history, to do this we simply have to add the replace
prop to the Navigate
component.
<Navigate replace to="/error-page" />
Without this prop, the browser will keep track of the history, including the redirect.
Programmatic Redirects with useNavigate()
You may be familiar with the useHistory()
hook from previous versions of the react-router-dom
package, which was used to programmatically redirect users. When visitors have finished filling out a form, or if you want to add a redirect function to a button, this is a great use-case.
The useHistory()
hook is first imported and then assigned to a variable, which is subsequently utilized in a button (for example) to redirect users once a specific action is taken. Using the onClick
event, we can then call the .push()
method to tell React Router where we want the button to redirect to.
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
import { useHistory } from 'react-router-dom';
const Home = () => {
const history = useHistory();
return (
{/* ... */}
<button onClick={() => history.push('/products')}>
{/* ... */}
);
};
With the release of React Router v6, we no longer utilize the useHistory()
hook, but instead the useNavigate()
hook, which is quite similar.
This is also accomplished by importing the hook and then assigning a variable to the useNavigate()
hook, like we did with useHistory()
. We can now utilize the variable that was returned to navigate the user to other pages.
import { useNavigate } from 'react-router-dom';
const Home = () => {
const navigate = useNavigate();
return (
{/* ... */}
<button onClick={() => navigate('/products')}>
{/* ... */}
);
};
Note: Unlike the useHistory()
hook, this does not require calling the push
method. All we need to do is pass the path as an argument to the navigate
function.
Conclusion
In this post, we looked at a number of ways to redirect with React Router, how it functions, and how this was handled in both the older version and the latest v6 version.