Create reusable components in React with {props.children}

Reusability of code is the most basic and fundamental part of writing the code.

Neha Sharma
Mar 18 · 3 min read

If you are not able to develop the reusable code then your skills need improvement. In Javascript, reusability is pretty easy by using OOPS, design patterns, classes, functions etc. If we talk about Reactjs reusability becomes tricky.

Generally, most the developers assume that if we are making components we can reuse the components many times. Which is true, though.

But think of those scenarios where we have to use the same components but with different requirements such as — content is different, UI is different, data is different.

Problem Statment:

In your app you have 3 types of buttons all of the buttons has different font-color and background color as well as text. Something like this:

Now, as a naive developer, you will end up creating three different components for buttons. However, here you will be breaking the law of the reusable code. You are actually ending up with non-reusable code.

How to solve this problem?

Solution: props.children

props.children gives you the feature to reuse the components by giving the container to put anything there. Basically, props. children give you a slot to put whatever you want to pass there and it will render between the component. So, now you will have the code like this of Button

So, now you have only one component at the place but you are reusing it three times in your application. This solved only one problem of the content and we still need to solve the theming problem. To handle the different theme we will create the different classes in CSS and try to customize it with props in Button component.

.btn-default, .btn-primary, .btn-secondary

Now, we have just one component of Button but we are reusing it three times with different content and classNames. This is the power of reusability and can be achieved by props.children. You can also have nested children(s) and it won’t be impacting your performance.

https://codesandbox.io/s/7403046mvx

So, next time while creating components, think of reusability. Remember Reactjs works on compose not inheritance.

JavaScript in Plain English

Learn the web's most important programming language.

Neha Sharma

Written by

Tech Lead; Brain behind JSLovers, Tech Speaker; ❤ Calligraphy and Chai. https://twitter.com/hellonehha; My Dev Journey: https://www.instagram.com/devgirllife/

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade