Table of Contents
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"56import { BrowserRouter } from "react-router-dom"78const 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"23function 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}2021function Home() {22 return <button>Go to dashboard</button>23}2425function Dashboard() {26 return <div>Dashboard</div>27}2829export default App
Navigating when the button is clicked
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"34function 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}2122function Home() {23 const navigate = useNavigate()2425 return (26 <button27 onClick={() => {28 navigate("/dashboard")29 }}30 >31 Go to dashboard32 </button>33 )34}3536function Dashboard() {37 return <div>Dashboard</div>38}3940export default App
Do follow me on twitter where I post developer insights more often!
Leave a Comment