How to Use Component Composition to Create a Flexible Compound Component in React

Creating solid and flexible React components following the composition pattern.

Marco Antonio Ghiani
Level Up Coding
Published in
5 min readNov 11, 2019

--

Photo by Gabriel Crismariu on Unsplash

When I started working with React, I immediately felt the flexibility that its API brings to frontend development. Creating a web component seems easier, and our ad-hoc elements do their job perfectly. As I began working as a JavaScript instructor at Codeworks and diving deeper into React, I also realized I was not properly exploiting the functionalities of this library, and I discovered there is much more than state and props for our components.

Knowing how to use the concepts of React, we could create incredibly flexible components able to fit multiple scenarios of our app. Inspired by Kent C. Dodds and his incredible contributions to the community, I want to help you to understand a different pattern to make your code more powerful.

What’s the problem?

We want to create a simple navbar that’s able to render a list of elements, and we want to show some of them only under certain circumstances. Let’s now assume that our navbar can show public elements to all the users, and some element only to those who are logged-in to the platform.

Photo by Olav Ahrens Røtne on Unsplash

The items in the navbar will be complex, and it should be able to handle different scenarios seamlessly. We need to create a component that uses a single prop to decide if some elements should render or not. Let’s start creating your first compound component!

Specify what you need for your component

Since we want to create a navbar with public and private characteristics, we need the Navbar component. This component should receive a prop to determine if an element is public or private, so we can keep it simple. We’ll use an isLogged<boolean> prop.

At this point, it is essential to define the role of this component. It will render any children and pass them this property (or any other props if we grew the application). But here comes the first…

--

--

“If it takes less than two minutes, then do it now.” D.A. Coding JS at @ Elastic. In love with coding.