Navigate Programmatically
Learn how to navigate the user programmatically in a React application.
We'll cover the following...
Introduction
In some cases, we’ll need to redirect the user to a specific URL when the user completes any action or task, such as submitting a form or creating an account.
To accomplish this, react-router
provides two ways to navigate users programmatically:
- The
useNavigate
hook - The
Navigate
element
1. Using the useNavigate
hook
The useNavigate
hook returns a function that we can use inside another function or in elements such as buttons to help navigate the user programmatically.
Use the coding widget given in the exercise to open the ContactDetails.js
file and paste the following code:
import React, { useEffect, useState } from "react";import { useParams, useSearchParams, useNavigate } from "react-router-dom";import { getContact } from "../Data";const ContactDetails = () => {let params = useParams();// console.log(params);const [contactData, setContactData] = useState();let [searchParams, setSearchParams] = useSearchParams();let navigate = useNavigate();useEffect(() => {let data = getContact(Number(params.contactId));// console.log(data);setContactData(data);}, [params]);const handleButtonClick = (event) => {event.preventDefault();navigate("../", { replace: true });};return (<div className="contactDetails"><h2 className="subTitle">Contact Details</h2>{contactData ? (<ul className="contact"><ol><strong>Name: </strong>{contactData.name}</ol><ol><strong>Number: </strong>{contactData.number}</ol><ol><strong>Email: </strong>{contactData.email}</ol>{searchParams.get("searchText") ? (<ol><strong>Search Value: </strong>{searchParams.get("searchText")}</ol>) : null}</ul>) : (<span>There is no data available for given contact Id.</span>)}<buttonclassName="back-btn"onClick={(event) => handleButtonClick(event)}>Go Back</button></div>);};export default ContactDetails;
Implement the useNavigate hook
Let’s take a look at the code line by line. For the ContactDetails.js
file:
Line 2: We import the ...