Home > Mobile >  Type json in React components
Type json in React components

Time:09-03

I have a dynamic json, for example:

{
    "first": "aaa",
    "second": "bbb",
    "other": "ttt"
}

And I created interface for this:

interface IResult {
    [key: string]: string;
}

I have two components:

function FirstComponent() {
    const [result, setResult] = useState<IResult>();

    useEffect(() => {
       setResult(some action);
    })

    return {
        <SecondComponent result={result}>
    }
}


function SecondComponent(result: IResult) {}

But this return me error:

Type "IResult" is not assignable to type 'string'.

in line: <SecondComponent result={result}>

What I'm doing wrong?

CodePudding user response:

When you pass arguments to a component, it is taken as props.

By defining SecondComponent as function SecondComponent(result: IResult) {}, you are declaring types of props as IResult and not the type of props.result as IResult.

Modify your declaration as following:

interface IProps {
 result: IResult
}

function SecondComponent(props: IProps) {}
  • Related