#6 of 100DaysOfCode
Atulit Anand
Posted on April 17, 2021
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.๐ผ
Posted on April 17, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.