What is a simple example of a higher order component that adds a border style to any component?
Short answer
A very simple higher order component can wrap any component in a div with a specific style, giving every wrapped component the same visual treatment without needing to add that styling code inside each individual component.
Advertisement
AModel answer
A very simple higher order component can wrap any component in a div with a specific style, giving every wrapped component the same visual treatment without needing to add that styling code inside each individual component.
function withBorder(WrappedComponent) {
return function BorderedComponent(props) {
return (
<div style={{ border: '2px solid gray', padding: '10px' }}>
<WrappedComponent {...props} />
</div>
);
};
}
const BorderedCard = withBorder(Card);Real-world example
A design system adds a consistent border and padding around several different card components using one shared withBorder higher order component, keeping the visual style consistent everywhere it is used.
Likely follow-ups
- How would you make the border color customizable instead of hardcoded?
- Could this same border behavior be achieved more simply using plain component composition?
Related topics