Home > Blockchain >  How to map render components that come from a JS Object without a temporary variable to hold them in
How to map render components that come from a JS Object without a temporary variable to hold them in

Time:10-03

So I came across some interesting code and I was wondering if its possible to "sugarize" it.

The components come as:

const sections = {
  Home: dynamic(() => import("./Sections/Home")),
  Example: dynamic(() => import("./Sections/Example")),
};

And then they are being rendered as:

export default function Page({ page }) { 

  return (
    <main>
      {page.sections.map((section, index) => {
        const SectionComponent = sections[section.type] || null;

        return (
          <SectionComponent
            key={`${pageKey}-${index}`}
            id={index}
            fields={section.fields}
          />
        );
      })}
    </main>
  );
}

So what would be the syntax to directly render

sections[section.type]({id: index, fields: section.fields})

to do something like this within the map, to reduce the code, without the SectionComponent variable in between?

CodePudding user response:

sections[section.type]({id: index, fields: section.fields})

There is not much to gain from what you suggest, on the contrary, in the above code now you are calling the component as a function vs rendering it an element as it was before, those are different things. In most of the cases you want to render it as element, otherwise you may get some unexpected behavior especially with hooks.

The code you came across is the recommended approach to do it.

  • Related