• Angular
  • React
  • NextJs
  • Sass

Navigate to Another Page on Button Click in React

By Webrecto, October 21, 2023

In this article, we will learn how to navigate to another page with the help of useNavigate() hook. Here we can redirect one page to the next or back page without using the Link component and return to the same page. so let's start to navigate programmatically using react-router.

What is React Router useNavigate() hook?

The latest react-router version 6 introduced a useNavigate() hook. It is a part of the react-router-dom package and is imported into the application from the same package. The useNavigate() hooks return a function that navigates the URL in the react application. This navigate() method allows programmatically routing inside the react project.

The useNavigate() is replaced useHistory() method and it does not accept the .push() or .replace() method. The navigate() method is used inside any click event and can set conditional calls to change the router path in the application. When clicking the event trigger by the user or self the navigate() method is active and sets a certain path in the browser. It smoothly changes one page to another page without page refresh.

Note: In the latest version of react-router-dom, The useHistory() hook has been deprecated.

Syntax

import { useNavigate } from "react-router-dom"
const navigate = useNavigate()
navigate(to, { state={}, replace=false })

The navigate method takes two parameters:

1: The first parameter is to pass the page path the same as which location you want to open the page.

2: The second parameter is optional.

The navigate method is very helpful in identifying the previous and next page when changing the react-router on the button click.

navigate("/employee"): It is navigate to a certain URL.

navigate(-1): It is navigate to the previous page.

navigate(1): It is navigate to the next page.

Note: The navigate(-1) and navigate(1) method works the same as the browser back and forward button.

Modifying the history stack

We can select to change the history stack, so we need to pass the delta in the history stack to which we want to go.

navigate(-1)

This is equal to the browser back button.

Project Structure

Navigate to Another Page on Button Click in React

In our example, we will set up a new project and will use the useNavigate() method to change the path by clicking the button.

Step 1: Create New Project

First, create a new project using the following command.

npx create-react-app navigate-to-another-page

Step 2: Install the latest react-router-dom and history

After project creation, Install the react-router-dom and history packages from the following command.

npm i react-router-dom history

After installation, we will find the latest version of the packages in the package.json

"history": "^5.3.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.17.0",

Step 3: Create Routing for Navigate to Another Page in an Application

In App.js, We will create routing and use 3 pages in the Route component for the change page from Link navigation.

App.js

import { Suspense, lazy } from "react";
import './App.css';
import { BrowserRouter as Router, Route, Link, Routes } from "react-router-dom";
import Dashboard from "./Dashboard";
import Employee from "./Employee";
import Customer from "./Customer";
import UserInfo from "./UserInfo";

function App() {
  return (
    <div className="App">
      <h2>Navigate to Another Page on Button Click in React::webrecto.com</h2>
      <Router>
        <div>
          <nav>
            <ul>
              <li><Link to="/">Dashboard</Link></li>
              <li><Link to="/employee">Employee</Link></li>
              <li><Link to="/customer">Customer</Link></li>
            </ul>
          </nav>
          <Routes>
            <Route path="/" element={<Dashboard />} />
            <Route path="/employee" element={<Employee />} />
            <Route path="/customer" element={<Customer />} />
            <Route path="/userinfo/:username" element={<UserInfo />} />
          </Routes>
        </div>
      </Router>
    </div>
  );
}
export default App;

Step 4: Redirect to another page on button click

I have created 3 components in a dummy project and used react routing for page navigation. In the employee component, I am using the navigate() method to button-click events. After clicking the button user will navigate the direct customer page.

Employee.js

import React from 'react';
import { useNavigate } from "react-router-dom";

const Employee = () => {
  const navigate = useNavigate()

  const gotToNewPage=()=>{
    navigate("/customer");
  }
  return (
    <>
      <h3>Employee List</h3>
      <button onClick={() => gotToNewPage()} className="btn">Go to Customer Page</button>
    </>
  );
};
export default Employee;

Step 5: Navigate to the Previous Page

When we pass -1 in the navigate() method, the page will redirect previous page.

Customer.js

import React from 'react';
import { useNavigate } from "react-router-dom"

const Customer = () => {
  const navigate = useNavigate()

  const goBack=()=>{
    navigate(-1);
  }
  return (
    <>
      <h3>Customer List</h3>
      <button onClick={()=>goBack()} className="btn">Go Back</button>
    </>
  );
};
export default Customer;

In the customer page, I am using the -1 value in the navigate() method to maintain navigation history. When we click goBack button the page will redirect to the employee page.

Step 6: Navigate to the Next Page

When we use the numeric number 1 in the navigation method, it reads the history of page routing, and the page changed to the next URL.

<button onClick={() => navigate(1)}>Go forward</button>

Change Dynamic Routing on button click

Dynamic routing is the best practice to set the page URL in run time when clicking the button on a certain user or row of data. We can set additional information in the page route with a variable and we can get the data on the next page with the userParams() hook.

Dashboard.js

import React from 'react';
import { useNavigate } from "react-router-dom";
const Dashboard = () => {
  const navigate = useNavigate();
  var userDetails =[
    {id:1, name: "WebRecto"},
    {id:2, name: "Shailendra"},
    {id:3, name: "Akhilesh"},
  ]
  const userInfo=(name)=>{
    navigate(`/userinfo/${name}`);
  }
  return (
    <>
      <h3>Dashboard</h3>
      <button onClick={()=>userInfo("My web")} className="btn">User Info</button>
      <ul className="user">
        {
          userDetails.map((user) => {
            return(
              <li onClick={()=> userInfo(user.name)}>{user.name}</li>
            )
          })
        }
      </ul>
    </>
  );
};
export default Dashboard;

UserInfo.js

import React from 'react';
import { useParams } from "react-router-dom";

const UserInfo = (props) => {
  const { username } = useParams();
  return (
    <h3>User Name - {username}</h3>
  );
};
export default UserInfo;

When the user clicks any name from the dashboard component, the browser path will show: http://localhost:3000/userinfo/WebRecto

Using the condition to redirect the another page in the React

In this example, we use some logic to render the navigate() method to redirect the users to a different page. The navigate() function is called only if the pagePath state is true and if the pagePath state is false it will not redirect to any page.

import React, {useState} from 'react';
import { useNavigate } from "react-router-dom";

const Employee = () => {
  const [pagePath, setPagePath] = useState(true)
  const navigate = useNavigate()

  const gotToNewPage=()=>{
    if(pagePath){
      navigate("/customer")
    }
    else{
      return null
    }
  }
  return (
    <>
      <h3>Employee List</h3>
      <button onClick={()=>gotToNewPage()} className="btn">Go to Customer Page</button>
    </>
  );
};
export default Employee;

Find the print screen of the output.

Navigate to Another Page on Button Click in React

Reference

Download Source Code