When I started using TypeScript with React, the first bump in the road was figuring out what type to use for the
children prop. That’s because there are several different types React provides for this. It didn’t help that I saw multiple projects using different types interchangeably.
In this post, I’ll cover each of the types you can use and discuss the trade-offs so you can pick the right one for your use case.
JSX.Element is the most restrictive type you can use for children. It works only if your
children prop is a single React element. It won’t work with anything else, including primitives, like strings:
JSX.Element is handy for restricting your
children prop to React element but too limiting for general use.
ReactChild allows for primitive, so it’s a more permissive alternative to
JSX.Element. However, ReactChild will not work with arrays. Look at this common use case of mapping to produce an array of elements:
Your first thought might be to allow an array of
ReacChild items as well, using
children: ReactChild | ReactChild. But the problem with this approach is that it doesn’t allow mixing a single element with arrays:
Plus, the type is getting a little too verbose. We can do better.
ReactNode is the go-to type if you want the
children prop to accept anything. It takes React elements, primitives, portals, fragments, etc.
children prop as
ReactNode is a perfectly viable option, but if you want to trim your code even further, you can use
React.FC is a standard type for components written using the arrow function. As you probably guessed,
FC stands for “Functional Component. "
React.FC assigns the
ReactNode type to the
children prop, so you don’t have to do it yourself.
To wrap up, use
ReactNode for the
children prop of your components unless you intend to make the prop more restrictive. You can use the
React.FC type on your arrow function components for brevity. I hope you found this post useful!
If you want to play around with the types yourself, here’s a sandbox for this tutorial.