Skip to main content

Setting Type for Props Passed to React Component in TypeScript

· One min read

We can create a simple React component as shown below:

const TodoList: React.FC = ({ todos }) => {
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
};

Above code complains that todos is not a valid props type. We can solve it by passing a generic type to React.FC explaining the props structure.

First create an interface defining the props structure:

interface TodoListProps {
items: {
id: string;
text: string;
}[];
}

Pass the interface as Generic type to component.

const TodoList: React.FC<TodoListProps> = ({ todos }) => {
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
};

This will fix the issue.