How to programmatically navigate using React Router

How to programmatically navigate using React Router image

In this post we cover how to programmatically navigate using React Router

When using React Router it is possible to programmatically navigate using the useNavigate hook.

1import { useNavigate } from "react-router-dom";
2
3export function CoffeeButton() {
4  const navigate = useNavigate();
5
6  function handleClick() {
7    navigate("/arabica-coffee");
8  }
9
10  return (
11    <button type="button" onClick={handleClick}>
12      Look at our coffee
13    </button>
14  );
15}

React Router

React Router is a client side router library built for use in React that helps with navigation in SPAs (Single Page Applications).

React

React or ReactJs is a library used for developing frontend applications. Its main concepts are based around state, props, and renders.

When a state variable or prop gets updated or changed, they trigger a render.

When a render happens the appropriate parts of the application essentially get re-built using the new values to provide a new UI to the user.

It is worth noting that a prop that causes a render is just a state variable that gets passed into another component.

Further resources

Related topics

Save code?

How to programmatically navigate using React Router code example image

© 2024 MWXYZ