Home > Mobile >  Typescript Error: Type '{ props: IDrink; }' is not assignable to type 'IntrinsicAttri
Typescript Error: Type '{ props: IDrink; }' is not assignable to type 'IntrinsicAttri

Time:06-13

I am getting this error in my React Typescript app. Specifically, the error is happening when trying to pass props to the child component.

Here is the parent component:


const SearchID: FC = (): ReactElement => {
    const { id } = useParams<string>();
    const {
        data: cocktails,
        isLoading,
        error
        } = useGetCocktailByIDQuery(id ? id : "");

    if(isLoading) return <Skeleton variant="text" />
    if(error) return <div>An error has occured.</div>

  return (
    <>
        {cocktails ? <CocktailDetail props={cocktails.drinks[0]} /> : "No data"}
    </>
  );
};

I am able to get the console.log(props) to show up in the console, but still getting the Typescript error. Child Component:

const CocktailDetail = (props: IDrink) => {
    console.log(props)
  return (
    <h1></h1>
  )
}

CodePudding user response:

  1. You do not explicitly specify types in your CocktailDetail component, so TypeScript is finding it hard to know what props should and shouldn't exist.
  2. The way you are passing props is slightly unconventional (not necessarily wrong).

What I tend to do is something like this:

interface IDrink {
    id: string;
    name: string;
}


interface CocktailDetailProps {
    drink: IDrink;
}

const CocktailDetail: FC<CocktailDetailProps> = ({ drink }) => {
    return (<h1></h1>);
}

Then use as follows:

const SearchID: FC = (): ReactElement => {
    const { id } = useParams<string>();
    const {
        data: cocktails,
        isLoading,
        error
        } = useGetCocktailByIDQuery(id ? id : "");

    if(isLoading) return <Skeleton variant="text" />
    if(error) return <div>An error has occured.</div>

  return (
    <>
        {cocktails ? <CocktailDetail drink={cocktails.drinks[0]} /> : "No data"}
    </>
  );
};
  • Related