React: props.children

Jeremy Wood
2 min readDec 5, 2021
Photo by Alp Duran on Unsplash

Code reusability is key in React. One nice tool we get for abstraction and reusability is props.children. Based on some explanations out there, it can take a second to understand exactly what’s happening in the code. However once you get it, it quickly becomes apparent how useful this feature could be. Basically, props.children is another way for us to dynamically change the JSX returned from our React components and functions.

When rendering a React component, we typically use a self closing tag, like this:

But, if we display a component with an opening and closing tag, everything between the component’s opening and closing tags is passed to the component as props.children.

In these examples we’re passing props to the component as we normally would, and we have access to props.someProps inside the ReactComponent. But you also have access to props.children. In this case, props.children contains a React element, which holds the JSX between our opening and closing Component tags. And if we drop props.children into the render portion of our ReactComponent, it will display that entire React element.

On the page, we would see the props we passed down normally inside the opening tag displayed, followed by any JSX passed down between our opening and closing tags. If we were to remove props.children from our return div, the “Some Heading” we passed in wouldn’t appear on the page.

This makes our ReactComponent very reusable, and can also come in handy if you don’t know what you’re going to be rendering inside of your component ahead of time. Maybe you have a navigation section or sidebar that needs to hold an image and a button in one tab, just some data in another, and a link in yet another. You could have a reusable sidebar item component that changes based on the JSX passed in between it’s call tags. This can help to keep logic out of the presentational sidebar item component itself, and in the containing sidebar component, which is key to reusability. You also have much less code in the way of messy props with different variable names being passed to a child component.

Hopefully this helped illustrate the very basics of props.children, and why it might be useful to you. Here are some good resources for further reading and uses.

Composition vs Inheritance - React Docs

A quick intro to React’s props.children - Jason Arnold

What is {this.props.children} and when you should use it?

--

--

Jeremy Wood

I’m a full stack engineer who loves to learn, solve problems, and fix things! When I’m not working on my code, you’ll usually find me working on my motorcycles.