Today was a regular day. All thanks to closures I was only able to learn just one new concept.
Higher-Order Components in React
Those are basically nothing but Higher-order functions.
So Higher-Order Components basically takes one component as input do something with it and return a new component and components are basically functions returning JSX markup (type of return value).
But get this, that is a new component after all even though it inherits the logic of original component.
const EnhancedComponent = higherOrderComponent(ComponentToBeWrapped)
And here is the code that shows beautiful use of closures.
const Speakers = ({ speakers }) => {
return (
<div>
{speakers.map(({ imageSrc, name }) => {
return (
<img src={`/images/${imageSrc}.png`} alt={name} key={imageSrc}></img>
);
})}
</div>
);
};
function withData(maxSpeakersToShow) {
return function(Component) {
const speakers = [
{ imageSrc: 'speaker-component-1124', name: 'Douglas Crockford' },
{ imageSrc: 'speaker-component-1530', name: 'Tamara Baker' },
{ imageSrc: 'speaker-component-10803', name: 'Eugene Chuvyrov' }
];
return function() {
// This is the place where magic happens
// How can this function access Components if its parent function have already executed?
return <Component speakers={speakers}></Component>;
};
};
}
export default withData(Speakers);
/*
Speakers are nothing but just the people who are supposed to give a presentation on the given day, like a regular TED talk.
*/
And my beautiful friends, I present Mr. Closure in front of you.
Returned child function can access environment variables of its parent and hence it can get the job done.
Little update from the comments
HOC(High order components) is an implementation of the decorator design pattern which consist in a component, that takes another component as parameter and return a new enanched component. In a nutshell, it adds logic(or behaviour) to the passed components without modifying it and its existent logic.
My view ?
Seperation of concerns demand seperation of UI logic (logic that makes UI visible as it is) and the application logic.
So we can use higher order components to do that.
Pass in our component with UI logic and let the HOC add data to it as in the example.
Hope this might have helped in any way.
I'd love to read your point of view about HOC.
Thanks for reading.ππ
Have a beautiful day.πΌ
Top comments (2)
Hi, I think that your code example is good but not your explanation.
HOC(High order components) is an implementation of the decorator design pattern which consist in a component, that takes another component as parameter and return a new enanched component. In a nutshell, it adds logic(or behaviour) to the passed components without modifying it and its existent logic.
Whatever, thank you for your posts. I find it really funny and useful.
π Thanks . I guess I was so busy admiring closures that I forgot about the main part.
I loved your defination.
Glad you liked it.