Home > database >  How to pass an object parameter via react-router-dom navigate
How to pass an object parameter via react-router-dom navigate

Time:10-28

I'm using useNavigate to navigate to another page. I need to pass an instance of an interface as a parameter when navigate to another page. Is there anyway to pass an interface instance as parameter?

The interface I want to pass as a paramemter:

export interface Api {
  apiDescription: string;
  apiName: string;
  documentId: string;
}

The code:

const { api, refresh } = props;
const navigate = useNavigate();
return (
    <div className="view-button-block">
      <Button
        size="small"
        sx={{ color: "#000000DE", bgcolor: "#D9D9D6" }}
        onClick={() => navigate("/managementUi/viewApi", { state: api })}
      >
        View
      </Button>
    </div>
  );

I want to pass api as a parameter when navigate to route "/managementUi/viewApi".

In viewApi.tsx the component I want to navigate to:

import React from "react";
import { useLocation } from 'react-router-dom';
import { Api } from '../../../common/Api.types';

const ViewApi = () => {
  const location = useLocation();
  console.log(location.state);
  const api: Api = location.state;
  return (
    <div>
      {location.state.apiName}
    </div>
  );
};

Update: I passed api as a state in navigate(). However, in the component I navigate to, when I try to read the apiName field from it, it has error for location.state that "Object is of type 'unknown'". What's the correct way to read apiName from location.state?

If I try to assign state to a declaration of api, it will has error "type unknown is not assignable to type Api"

CodePudding user response:

You will recast the location.state as an object with the Api interface.

Example:

import { Api } from '../../../common/Api.types';

...

const ViewApi = () => {
  const location = useLocation();
  const api = location.state as Api;

  console.log(api);
  return (
    <div>
      <ViewHeader apiName={api.apiName} />
    </div>
  );
};
  • Related