DEV Community

Cover image for Programmatically Navigate Using React Router
collegewap
collegewap

Posted on • Originally published at codingdeft.com

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:

npx create-react-app react-router-programmatic-routing
Enter fullscreen mode Exit fullscreen mode

Now install react-router-dom and history packages:

npm i react-router-dom history
Enter fullscreen mode Exit fullscreen mode

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

import React from "react"
import ReactDOM from "react-dom/client"
import "./index.css"
import App from "./App"

import { BrowserRouter } from "react-router-dom"

const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>
)
Enter fullscreen mode Exit fullscreen mode

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

import { Link, Route, Routes } from "react-router-dom"

function App() {
  return (
    <div className="App">
      <nav>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
        </ul>
      </nav>
      <Routes>
        <Route path="/" element={<Home />}></Route>
        <Route path="dashboard" element={<Dashboard />}></Route>
      </Routes>
    </div>
  )
}

function Home() {
  return <button>Go to dashboard</button>
}

function Dashboard() {
  return <div>Dashboard</div>
}

export default App
Enter fullscreen mode Exit fullscreen mode

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.

import { Link, Route, Routes } from "react-router-dom"
import { useNavigate } from "react-router-dom"

function App() {
  return (
    <div className="App">
      <nav>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
        </ul>
      </nav>
      <Routes>
        <Route path="/" element={<Home />}></Route>
        <Route path="dashboard" element={<Dashboard />}></Route>
      </Routes>
    </div>
  )
}

function Home() {
  const navigate = useNavigate()

  return (
    <button
      onClick={() => {
        navigate("/dashboard")
      }}
    >
      Go to dashboard
    </button>
  )
}

function Dashboard() {
  return <div>Dashboard</div>
}

export default App
Enter fullscreen mode Exit fullscreen mode

Top comments (0)