Render Props are perhaps one of the most underrated design patterns in React. I call it underrated because even developers who have been using React for years do not use this pattern as much as it should to be used.
We're going to continue with our Dropdown
component.
Flock has many such components, which look like:
You might have noticed that all of these components have similar logic - User clicks on a CTA (Call-To-Action) and the
Dropdown
opens up. When the user clicks anywhere else, theDropdown
closes.
So, what this means is the component's state logic remains the same, however, the content in the component is never the same.
Let's begin with component composition - the most basic version of our component that will solve this problem.
Component Composition
import React, { Component } from "react";
import "./Dropdown.css";
export default class Dropdown extends Component {
state = {
show: false
};
toggle = () => {
this.setState(({ show }) => ({
show: !show
}));
};
render() {
const { show } = this.state;
const { children, label, onToggle } = this.props;
return (
<div className="dropdown">
<span className="cta" onClick={this.toggle}>
{label}
</span>
{show ? <div className="content">{children}</div> : null}
</div>
);
}
}