Categories
React Answers

How to pass state to another component with react-router-dom v6 useNavigate hook?

Spread the love

To pass state to another component with react-router-dom v6 useNavigate hook, we can call navigate with an object as the 2nd argument.

For instance, we write

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

const ComponentA = (props) => {
  const navigate = useNavigate();

  const toComponentB = () => {
    navigate("/componentB", { state: { id: 1, name: "sabaoon" } });
  };

  return (
    <>
      <div>
        <a onClick={() => toComponentB()}>Component B</a>
      </div>
    </>
  );
};

export default ComponentA;

to call navigate with the "/componentB" URL path and an object that we want to pass to the component that renders when we go to /componentB.

Then in ComponentB, which is rendered when we go to /componentB, we get the values from the useLocation hook by writing

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

const ComponentB = () => {
  const location = useLocation();

  return (
    <>
      <div>{location.state.name}</div>
    </>
  );
};

export default ComponentB;

We call the useLocation hook to return the object that we passed in as the 2nd argument of navigate in ComponentA.

And then we get the properties from the location object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *