Skip to content

Instantly share code, notes, and snippets.

@jakoblind
Created March 20, 2017 10:13
Show Gist options
  • Save jakoblind/c84f1668b299e56fa83d50e9ca63076e to your computer and use it in GitHub Desktop.
Save jakoblind/c84f1668b299e56fa83d50e9ca63076e to your computer and use it in GitHub Desktop.
React higher order component for empty component logic
//Problem description: I have a lot of small components that render an EmptyCartSection if a certain input prop is empty (different props for different components). The code looks like this:
const TotalMonthly = (({ cartContainsStuff, usefulProps }) => {
if (!cartContainsStuff) {
return <EmptyCartSection />;
}
return (
// The actual implementation. Not relevant here.
);
});
//The if check is pretty repetitative so let's extract it to a higher order component!
const renderEmptyComponentOnEmptyProp = (propName) => (WrappedComponent) => {
return class extends React.Component {
render() {
if (!this.props[propName]) {
return <EmptyCartSection />;
}
return (
<WrappedComponent
{...this.props}
/>
);
}
};
};
//Now our TotalMonthly component looks like this:
const TotalMonthly = renderEmptyComponentOnEmptyProp("containsMonthlyFees")(({ usefulProps }) => {
return (
// The actual implementation. Not relevant here.
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment