type CardProps = {
title: string;
variant?: "primary" | "ghost";
children: React.ReactNode;
};
function Card({ title, variant = "primary", children }: CardProps) {
return <section className={variant}><h2>{title}</h2>{children}</section>;
}
Declare a type or interface for the props and annotate the destructured parameter. Type children as React.ReactNode. React.FC also works, but plain functions are now more common.
- Optional props use
?and get default values in the destructuring, likevariant = "primary". - Either
typeorinterfaceworks. Pick one convention.
React.ReactNode covers everything React can render: elements, strings, numbers, arrays, null and so on. If a component must receive children, make the prop required. If not, add ?.
React.FC<Props> also works. Since the React 18 types, it no longer adds children for you, so you declare children either way.
Many codebases now prefer plain function declarations with typed props. They read like normal functions and work naturally with generics. But this is a style choice.
- Write props as a
typeorinterface, and annotate the function parameter. - Mark optional props with
?and give them defaults in the destructuring. - Type
childrenasReact.ReactNode. - Since the React 18 types,
React.FCno longer addschildrenfor you. - Plain functions are common, and they are simpler with generics.
Read more