Member-only story
Master the Compound Component Pattern
Write declarative React components using an advanced pattern
Today I would like to introduce a simple yet powerful way to create components with ReactJS: The compound component pattern.
What’s a compound component?
The compound component pattern allows components to share an implicit state. This allows us to create expressive and declarative components, without unnecessary prop drilling. The components work together to accomplish a shared task.
A good example is the HTML select
and option
.
<select>
<option value="apple">Apple</option>
<option value="pear">Pear</option>
</select>
Option
and select
work together to accomplish their goal of allowing a user to select their favourite fruit.
The previous example is native HTML. What would the React equivalent look like?
Here’s how it looks without the compound component pattern:
<Select
value={value}
onChange={handleChange}
options={[
{ value: "apple", label: "Apple" },
{ value: "pear", label: "Pear" }
]}
/>;
Here’s what it looks like with the compound component pattern:
<Select value={value} onChange={handleChange}>
<Select.Option value="apple">Apple</Select.Option>
<Select.Option value="pear">Pear</Select.Option>
</Select>;
As you can see, our component is now expressed in a more declarative fashion.
Let’s put the compound component pattern into action and create our own Input
component.
Putting the Pattern Into Action
We want to create an Input
component that’s flexible enough to meet all of our needs.
Acceptance criteria
- Labels can be placed before or after the input.
- Custom elements like icons or buttons can be placed before or after the input.
- It should also allow passing in custom elements like icons or buttons.
- When the input has focused, the entire area should have focus.
- The component…