Search code examples
reactjstypescriptreact-hookstsxreact-tsx

Property 'detail' does not exist on type '{}'.ts(2339)


I get the error in the title in code below, how do I fix it?

  • Any help is appreciated!

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

let history = useHistory();
    history.push({
        pathname: '/otherPage',
        state: { detail: id }
    });

//otherPage
import React, { useEffect } from 'react';
import { useLocation } from "react-router-dom";

const location = useLocation();
    useEffect(() => {
        console.log(location.state.detail);
    }, [location]);

Solution

  • Welcome to StackOverflow.

    The problem with your code is that the state part of the location is user defined. So, what you would need to do, assuming you know what you have populated in the state, is to specify the type of state you have:

    interface State {
      detail: string;
    }
    
    const location = useLocation<State>();
    useEffect(() => {
        console.log(location.state.detail);
    }, [location]);