How to pass React components as props in TypeScript

#react #typescript

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



1. Create ItemsList Component


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} />
      ))}
    </>
  );
}


2. Create Item Component


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



Suraj Sharma is a JavaScript Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.