Skip to content
react

Programmatically Navigate Using React Router

Oct 18, 2022Abhishek EH2 Min Read
Programmatically Navigate Using React Router

Do you want to redirect a user to another page when a certain event like a button click happens? Are you using react-router in your application for handling routing? Then in this article, we will see how to navigate programmatically using react-router.

Project setup

Create a new react project using the following command:

1npx create-react-app react-router-programmatic-routing

Now install react-router-dom and history packages:

1npm i react-router-dom history

In index.js, wrap the App component with BrowserRouter:

index.js
1import React from "react"
2import ReactDOM from "react-dom/client"
3import "./index.css"
4import App from "./App"
5
6import { BrowserRouter } from "react-router-dom"
7
8const root = ReactDOM.createRoot(document.getElementById("root"))
9root.render(
10 <React.StrictMode>
11 <BrowserRouter>
12 <App />
13 </BrowserRouter>
14 </React.StrictMode>
15)

In App.js create a couple of routes one for the home and another for the dashboard:

App.js
1import { Link, Route, Routes } from "react-router-dom"
2
3function App() {
4 return (
5 <div className="App">
6 <nav>
7 <ul>
8 <li>
9 <Link to="/">Home</Link>
10 </li>
11 </ul>
12 </nav>
13 <Routes>
14 <Route path="/" element={<Home />}></Route>
15 <Route path="dashboard" element={<Dashboard />}></Route>
16 </Routes>
17 </div>
18 )
19}
20
21function Home() {
22 return <button>Go to dashboard</button>
23}
24
25function Dashboard() {
26 return <div>Dashboard</div>
27}
28
29export default App

We can use the useNavigate hook from react-router to navigate to the dashboard when the button is clicked.

App.js
1import { Link, Route, Routes } from "react-router-dom"
2import { useNavigate } from "react-router-dom"
3
4function App() {
5 return (
6 <div className="App">
7 <nav>
8 <ul>
9 <li>
10 <Link to="/">Home</Link>
11 </li>
12 </ul>
13 </nav>
14 <Routes>
15 <Route path="/" element={<Home />}></Route>
16 <Route path="dashboard" element={<Dashboard />}></Route>
17 </Routes>
18 </div>
19 )
20}
21
22function Home() {
23 const navigate = useNavigate()
24
25 return (
26 <button
27 onClick={() => {
28 navigate("/dashboard")
29 }}
30 >
31 Go to dashboard
32 </button>
33 )
34}
35
36function Dashboard() {
37 return <div>Dashboard</div>
38}
39
40export default App

If you have liked article, stay in touch with me by following me on twitter.

Leave a Comment

© 2022 CodingDeft.Com