Home > front end >  How to pass props to a component
How to pass props to a component

Time:08-25

Type '{ data: { title: string; }[]; }' is not assignable to type 'IntrinsicAttributes & PropsT'. Property 'data' does not exist on type 'IntrinsicAttributes & PropsT'.

const ParentComp = () => {
  const values = [
    { title: 'someText' }
  ]
  return <ChildComp data={values} /> // WARNING
}

type PropsT = [
  { title: string }
]
const ChildComp = (data: PropsT) => {
  return <>{data[0].title}</>
}

CodePudding user response:

There's two problems:

const ChildComp = (data: PropsT) => {

Here, data is the props given. It's an object. You probably meant to destructure this:

const ChildComp = ({ data }: PropsT) => {

The props type PropsT should reflect this:

type PropsT = {
    data: { title: string; }[];
};

Another change was [{ title: string }] to { title: string }[].

The former is a tuple with only one element, while the latter is an array. Tuples have fixed lengths while arrays can have as many elements as it wants.

  • Related