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?
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?
Share Improve this question asked Apr 25, 2020 at 20:20 ciz30ciz30 4533 gold badges12 silver badges19 bronze badges2 Answers
Reset to default 11You 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>
)
}
Added to the reply, if the props can be null, you put a question mark.
interface ChildComponentProps {
items?: Item[]
}