This content originally appeared on DEV Community and was authored by atulit023
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).
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.
Hope this might have helped in any way.
Thanks for reading.??
Have a beautiful day.?
This content originally appeared on DEV Community and was authored by atulit023
atulit023 | Sciencx (2021-04-17T14:50:08+00:00) #6 of 100DaysOfCode. Retrieved from https://www.scien.cx/2021/04/17/6-of-100daysofcode/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.