Tuesday, 21 January 2025

Programmatic Navigation in React with the useNavigate Hook

React Router is a powerful library that allows developers to create dynamic routing in React applications. One of its essential features is the useNavigate hook, which enables programmatic navigation. This hook is particularly useful for navigating between routes based on user interactions, such as button clicks, form submissions, or even API responses. In this blog post, we will explore how to use the useNavigate hook effectively to enhance user experience in your React applications.

What is useNavigate?

useNavigate is a hook provided by React Router (version 6 and above) that allows you to programmatically navigate to different routes within your application. It replaces the older useHistory hook and simplifies the navigation process by providing a straightforward API.

 

How to Use useNavigate

To use useNavigate, you need to,

 

1.   Import the hook from react-router-dom.

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

2.   Call the hook within your component to obtain the navigate function.

const navigate = useNavigate();

3.   Use the navigate function to redirect users to the desired route.

navigate('/about'); // Navigate to the about page

 

Let’s build a simple application to understand useNavigate hook better.

 

Step 1: Go to the post (Quickly Set Up a React Project with Vite: A Step-by-Step), and set up a React Project ‘use-navigate-demo’.

 

Project structure looks like below.

 


Step 2: Install react router dependency.

 

To implement routing, we need to install the react-router-dom package. This will allow us to use React Router for navigation.

 

Go to the project root folder and execute below command.

npm install react-router-dom

 

Step 3: Create pages folder in src folder and define Home, About and Contact pages.

 

AboutPage.jsx

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.jsx'
import "./styles.css";
createRoot(document.getElementById('root')).render(
  <StrictMode>
    <App />
  </StrictMode>,
)

 

ContactPage.jsx

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

export default function ContactPage() {
  const navigate = useNavigate();

  function gotoHome() {
    navigate("/");
  }

  return (
    <>
      <h3>Contact Page</h3>
      <button className="nav-button" onClick={gotoHome}>
        Home
      </button>
    </>
  );
}

 

HomePage.jsx

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

export default function HomePage() {
  const navigate = useNavigate();

  function gotoAbout() {
    navigate("/about");
  }
  function gotoContact() {
    navigate("/contact");
  }
  return (
    <>
      <h3>Home Page</h3>
      <button className="nav-button" onClick={gotoAbout}>
        About
      </button>
      <button className="nav-button" onClick={gotoContact}>
        Contact
      </button>
    </>
  );
}

Step 4: Create styles.css file in src folder.

 

styles.css

.nav-button {
    display: inline-block;           /* Makes the anchor behave like a button */
    padding: 10px 20px;              /* Add padding for better click area */
    text-decoration: none;           /* Remove underline */
    background-color: #007BFF;       /* Button-like background color (blue) */
    color: white;                    /* Text color */
    border-radius: 5px;              /* Rounded corners */
    font-size: 16px;                 /* Set font size */
    transition: background-color 0.3s ease;  /* Smooth background color transition */
    border: none;                    /* Remove border */
    cursor: pointer;                 /* Pointer cursor to indicate clickability */
    margin: 10px;
}

.nav-button:hover {
    background-color: #0056b3;       /* Darker background color on hover */
    text-decoration: none;           /* Keep underline removed on hover */
}

.nav-button:active {
    background-color: #003d80;       /* Even darker color on click */
}

 

Step 5: Update App.jsx with below content.

 

App.jsx

 

import { BrowserRouter, Routes, Route, useNavigate } from "react-router-dom";
import HomePage from "./pages/HomePage";
import AboutPage from "./pages/AboutPage";
import ContactPage from "./pages/ContactPage";

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<HomePage />} />
        <Route path="/about" element={<AboutPage />} />
        <Route path="/contact" element={<ContactPage />} />
      </Routes>
    </BrowserRouter>
  );
}

export default App;

Step 6: Update main.jsx with below content.

 

main.jsx

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.jsx";
import "./styles.css";

createRoot(document.getElementById("root")).render(
  <StrictMode>
    <App />
  </StrictMode>
);

Step 7: Build and run the application by executing below commands.

  cd use-navigate-demo
  npm install
  npm run dev

Open the url ‘http://localhost:5173/’ in browser, you will see below screen.



Click on About button, you will be navigate to About page.


 


You can download this application from this link.

 

Restrictions on useNavigate hook

There are some restrictions and best practices around where you can use the useNavigate hook in React.

 

1. Inside React Functional Components (Allowed)

The useNavigate hook can only be used inside React functional components (or custom hooks). It is a React hook, and like all hooks, it follows the Rules of Hooks. This means you cannot use it outside of a React component function or a custom hook.

 

2. Cannot Use in Class Components (Not Allowed Directly)

React hooks, including useNavigate, cannot be used directly in class components. If you are working with class components and want to use useNavigate, you have two options:

 

Convert the class component to a functional component.

Use the Navigate component from react-router-dom for redirecting (Ex: <Navigate to="/profile" />).

 

3. Not Inside Non-Component Utility Functions (Not Allowed)

You cannot use useNavigate in non-component utility functions or outside the component tree. Hooks rely on React’s context and lifecycle, which means they must be used directly within components that are part of the React tree.

 

4. Within Custom Hooks (Allowed)

You can wrap useNavigate inside a custom hook. This allows you to reuse navigation logic across multiple components in your application.



Previous                                                    Next                                                    Home

No comments:

Post a Comment