Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 17, 2021 02:50 pm GMT

6 of 100DaysOfCode

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.


Original Link: https://dev.to/icecoffee/6-of-100daysofcode-47ge

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To