12

I'm using React and TypeScript and trying to pass some data like prop to child component and use it in child component. But i'm getting error and i can't understand why is happened and how fix it. I'm beginner on TypeScript also.

Here is my parent component

import * as React from "react";
import ChildComponent from "./ChildComponent";

const data = [
  {
    title: "A",
    id: 1,
  },
  {
    title: "B",
    id: 1,
  },
];

const ParentComponent = () => {
   return (
      <ChildComponent items={data} />
   )
}

export default ParentComponent;

Here is error in parent component at items

(JSX attribute) items: {
    title: string;
    id: number;
}[]
Type '{ items: { title: string; id: number; }[]; }' is not assignable to type 'IntrinsicAttributes'.
  Property 'items' does not exist on type 'IntrinsicAttributes'.ts(2322)

And when in regular react and es6 i can use this props in child component like this:

const ChildComponent = (props) => {
   return (
      <div>
         {props.items.map((item) => (
           <p to={item.title}></p>
         ))} 
      </div>
   )
}

but have use this props in child component if it will be TypeScript?

2 Answers 2

11

You need to specify what type of props the child component wants. For example:

interface Item {
  title: string;
  id: number;
}

interface ChildComponentProps {
  items: Item[]
}

const ChildComponent: React.FC<ChildComponentProps> = (props) => {
  return (
    <div>
      {props.items.map((item) => (
        <p to={item.title}></p>
      ))} 
    </div>
  )
}
Sign up to request clarification or add additional context in comments.

2 Comments

And on parent component nothing to do? Just need to assign types to child component right?
To fix the error you're seeing nothing should be needed in the parent. If the parent has props though, it should get similar treatment. Even if it doesn't have props, it's probably best to give it a type anyway, just without any props: const ParentComponent: React.FC = () => {
2

Added to the reply, if the props can be null, you put a question mark.

interface ChildComponentProps {
  items?: Item[]
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.