There are two main ways to programmatically navigate to an URL with React:
- using the
window.location
object (if the app does not uses React Router) - using the React Router
useNavigate()
hook
This article will show you how to use both approaches.
Programmatically navigate in React using window location
The window.location is the goto tool when you want to navigate to a specific URL and your React app is not managed by the React Router.
We can use one of the below approaches:
//โ๏ธwill not be able to use browser's back button
window.location.replace(url)
// ok to use browser's back button
window.location.href = url
The first line will not create a new browser history entry, therefore the back will not work. While the second button will create the entry as clicking on a normal <a href="...">
will do.
I've made a small React app to illustrate this:
And below is the code for it:
const NavigateLocReplace = ({url}) => {
// will not be able to use window back
const navigate = ()=> window.location.replace(url)
return (<button onClick={navigate}>
๐ด Navigate using window.location.replace
</button>)
}
const NavigateLocHref = ({url}) => {
// ok to use window back
const navigate = ()=> window.location.href = url
return (<button onClick={navigate}>
๐ต Navigate using window.location.href
</button>)
}
const App = () => {
return (<div>
<NavigateLocReplace url="https://www.js-craft.io/" />
<NavigateLocHref url="https://www.js-craft.io/" />
</div>)
}
You can see here the Github repo for it, and here is the live working example.
Navigate using the React Router v6 and above with useNavigate() hook
Starting from version 6.0.0
of React Router we have a new hook named useNavigate() that handles the programmatic navigation.
Below you have an example of a React app that uses this hook:
import { useEffect } from 'react';
import { Route, Routes, useNavigate } from 'react-router-dom';
const Index = ()=> {
const navigate = useNavigate();
useEffect(() => {
setTimeout(
() => navigate('/welcome', { replace: true })
, 3000);
}, []);
return <>Redirecting to the Welcome page.</>;
}
const App = ()=> {
return (
<Routes>
<Route path="/" element={<Index />} />
<Route path="welcome" element={<> ๐ Welcome </>} />
</Routes>
)
}
We can pass in a delta (an integer number) to the useNavigate()
hook and go back and forth in the browser's history:
const navigate = useNavigate()
// ๐ goes back like the browserโs โBackโ button
navigate(-1)
// ๐ goes forward like the browserโs โForwardโ button
navigate(1)
React Router v5 and useHistory (legacy)
React Router version 5 had a similar method called useHistory(), which served a similar purpose as the useNavigate() hook introduced in later versions.
If you're using version 5 or earlier, here's how you can navigate to an URL:
import React from 'react';
import { useHistory } from 'react-router-dom';
const App = () => {
const history = useHistory();
const handleClick = () => history.push('/exit');
return (
<button type="button" onClick={handleClick}>
Goodbye ๐๐๐
</button>
);
};
๐ 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.
๐ 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.