Created
March 20, 2017 10:13
-
-
Save jakoblind/c84f1668b299e56fa83d50e9ca63076e to your computer and use it in GitHub Desktop.
React higher order component for empty component logic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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