1

I've tried to get an object from props.location.state but TypeScript is giving me an error. This is the only way I could get the object from state:

import React, { FC } from 'react';
import { RouteComponentProps } from 'react-router-dom';

import AssetData from '../interfaces/dataInterface';

type Props = {
    location: RouteComponentProps;
};

const DetailPage: FC<Props> = ({ location }: Props) => {
    const { state }: any = location;
    const data: AssetData = state.movieData;

    return <div style={{ fontSize: '65px', marginTop: '100px' }}>{data?.title}</div>;
};

export default DetailPage;
Edaurd B
  • 173
  • 1
  • 9
  • Does this answer your question? [What TypeScript type should I use to reference the match object in my props?](https://stackoverflow.com/questions/48138111/what-typescript-type-should-i-use-to-reference-the-match-object-in-my-props) – r3dst0rm Aug 17 '20 at 11:56
  • I can set a type for location but it still not working for state, even though RouteComponentProps covers this prop: state: S; . Those answers are not working. I've tried those before asking this question. – Edaurd B Aug 17 '20 at 12:02

1 Answers1

0

You can access the state prop by defining the interface of the state as a generic for RouteComponentProps<InterfaceA, InterfaceB, InterfaceForState>.

Please see the following:

import React, { FunctionComponent } from "react";
import { RouteComponentProps } from "react-router-dom";

type Props = {
  location: RouteComponentProps<{ bla: string }, {}, { state: string }>;
};

const DetailPage: FunctionComponent<Props> = (props) => {
  const yourStateProp = props.location.location.state;

  return (
    <div style={{ fontSize: "65px", marginTop: "100px" }}>
      {JSON.stringify(yourStateProp)}
    </div>
  );
};

export default DetailPage;

The above is equivalent to this:

import React, { FunctionComponent } from "react";
import { RouteComponentProps } from "react-router-dom";

type Props = {
  location: RouteComponentProps<{ bla: string }, {}, { state: string }>;
};

const DetailPage: FunctionComponent<Props> = ({ location: { location: { state }}}) => {
  return (
    <div style={{ fontSize: "65px", marginTop: "100px" }}>
      {JSON.stringify(state)}
    </div>
  );
};

export default DetailPage;

The state object is now equal to the previous defined { state: string; } interface and can be used in a type-safe manner.

r3dst0rm
  • 1,876
  • 15
  • 21