GrillOwner69420
GrillOwner69420

Reputation: 825

How to pass parameters with React-router-dom version 6 useNavigate and typescript

I am trying to send the variable id to another page using useNavigate in react-router-dom version 6. Here is what I am trying:

const handleSelect = (id: number) => {
    navigate('/Players', {
      userId: id,
    });
  };

However I I am getting the error: Argument of type '{ userId: number; }' is not assignable to parameter of type 'NavigateOptions'. Object literal may only specify known properties, and 'userId' does not exist in type 'NavigateOptions'.ts(2345)

I can't find any useful information on NavigateOptions or what type it is looking for. If I remove the parameter userId then I can navigate to the Player page just fine. It is just the parameter that is causing the problem. What can I do about this issue? Could someone provide some documentation on this?

What would be an example of a parameter that is of type NavigateOptions?

Upvotes: 20

Views: 50353

Answers (3)

MattWeiler
MattWeiler

Reputation: 790

When redirecting the user to the /Players page you need to send the meta-data in the state property of the options:

const handleSelect = (id: number) => {
    navigate('/Players', {
      state: {
        userId: id,
      }
    });
  };

You can then access the state by using location.state.userId in the Players page.

But for Typescript, you'll likely have to cast the state:

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

const location = useLocation();
const locationState = (location.state as {userId? : number});

// get userId
let userId = locationState.userId;

Upvotes: 2

Jimmy Metz
Jimmy Metz

Reputation: 432

Did you mean to add state to the navigation? Original:

const handleSelect = (id: number) => {
    navigate('/Players', {
      userId: id,
    });
  };

Changed to (with state):

const handleSelect = (id: number) => {
    navigate('/Players', {
      state: {
        userId: id,
      }
    });
  };

Then you can reference props.location.state.userId in the Players page.

// Players Page

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

const location = useLocation();

// get userId
let userId = location.state.userId;

Upvotes: 35

Balazs Toth
Balazs Toth

Reputation: 37

In the Players page the "props.location.state.userId" will not work anymore. Do this in the Players page:

import { useLocation } from "react-router-dom";
const location = useLocation();
location.state.userId

Upvotes: 2

Related Questions