Search⌘ K
AI Features

How Control Props Work

Explore how control props enable React components to have their state managed externally or internally. Understand the implementation details of controlled components like Expandable, including toggling state and handling callbacks, to enhance component flexibility and interaction.

Controlled vs. Uncontrolled Elements

Consider a simple input field.

Javascript (babel-node)
<input />

In React, a controlled input element will be defined like this:

Javascript (babel-node)
<input value={someValue} onChange={someHandler} />

Hmm, that’s different.

A controlled input component has its value and onChange handler managed externally.

This is exactly what we aim for when implementing the control props pattern. We want the internally-managed state to be manageable from the outside via props!

Implementing in Expandable

How it Works

The implementation is quite simple, but we need to understand how it works before we delve into writing some code.

The default usage of the Expandable component is as shown below:

Javascript (babel-node)
<Expandable>
<Expandable.Header>
{someHeader}
</Expandable.Header>
<Expandable.Icon />
<Expandable.Body>{someContent}</Expandable.Body>
</Expandable>

Within the Expandable component, the expanded value is internally managed and communicated to the children. ...