Components 7 exercises
solution

Typing React's Children

The correct way to handle this is by adding children into the props, and have it be typed as React.ReactNode.


export const Button = (props: { children: React.ReactNode }) => {
return <button>{props.children}</button>;
};

The React.ReactNode covers all of the different cas

Loading solution

Transcript

0:00 The correct way to handle this is by adding children into the props. This children property is going to be typed as React.ReactNode. Now, this React.ReactNode, what it does is it covers all of the different cases where you can pass children in. It's perfect for this case. You might be tempted to use React.ReactChild or something. This is deprecated.

0:23 React.ReactNode is the one. If we command-click on it and we can actually see all of the different things that can potentially go into React.Node. It's like a helper type really. We've got ReactElement, string, number, React Fragment, React Portal, boolean, , or undefined.

0:39 We don't need to worry about the composition of ReactElement. I'm going to get into that in a future video. You should know that React.Node is a great way to express all of the different things that you can pass in into that slot. Now, what this means then is that actually this children is enforced to be there. We have to pass children now.

1:00 If I don't pass children, what you're going to see is it's actually going to yell at me because property children is missing in typed empty object. This can be worked around a little bit. You notice if I leave a space there, then technically that space is a child, which is a little bit funky. If I do this as well then technically I am passing in children.

1:18 It works a little bit funky with Prettier as well. You get the idea. Now we have to pass a set of children into there, which is super duper useful. React.ReactNode incredibly useful, really good for avoiding the any problem when it comes to children.