Last updated on Nov 29, 2020 by Suraj Sharma
In this tutorial, you will learn how you can pass a component as props to other components in React and Typescript
I am using Typescript to strongly-type the components props
Consider you have a component <Item>
and want to pass it as props to another component <ItemsList />
, which iterates through an array of objects and renders <Item />
for each object
First, we are going to create a ItemsListProps
to type the props
./ItemsList.tsx
type ItemsListProps = {
component: React.ReactNode
}
Now, create and type the function component ItemsList
with component
as the only props of it,
const ItemsList:React.FC<ItemsListProps> = ({
component:Component
}) => {
const [items, setItems] = React.useState([
{id: 1, name: 'Orange'},
{id: 2, name: 'Apple'},
{id: 3, name: 'Stawberry'},
])
return (
<>
{items.map(item=>(
<Component item={item} />
))}
</>
);
}
Let's create and type the Item
component, which takes the item
object as props
./Item.tsx
type ItemType = { id: number, name: string }
type ItemProps = {
item: ItemType
}
const Item: React.FC<ItemProps> = ({
item
}) => {
return (
<div key={item.id}>{item.name}</div>
);
}
Related Solutions
Call parent component method in a child component in React and Typescript
How to pass props to the makeStyles API in React Material UI
Rate this post
Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.