This page looks best with JavaScript enabled

Using React children prop with TypeScript

 ·  ☕ 2 min read  ·  ✍️ Iskander Samatov

React children prop with TypeScript


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

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
JSX element

JSX.Element is handy for restricting your children prop to React element but too limiting for general use.

React.ReactChild

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:

ReactChild
ReactChild

Your first thought might be to allow an array of ReacChild items as well, using union types children: ReactChild | ReactChild[]. But the problem with this approach is that it doesn’t allow mixing a single element with arrays:

ReactChild combined
ReactChild combined

Plus, the type is getting a little too verbose. We can do better.

ReactNode

ReactNode is the go-to type if you want the children prop to accept anything. It takes React elements, primitives, portals, fragments, etc.

ReactNode
ReactNode

React.FC

Declaring the children prop as ReactNode is a perfectly viable option, but if you want to trim your code even further, you can use React.FC. React.FC is a standard type for components written using the arrow function. As you probably guessed, FC stands for “Functional Component. "

React.FC
React.FC

React.FC assigns the ReactNode type to the children prop, so you don’t have to do it yourself.

Conclusion

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.

If you’d like to get more web development, React and TypeScript tips consider following me on Twitter, where I share things as I learn them.
Happy coding!

Share on

Software Development Tutorials
WRITTEN BY
Iskander Samatov
The best up-to-date tutorials on React, JavaScript and web development.