Home > Enterprise >  React Custom Hook that returns array of Components
React Custom Hook that returns array of Components

Time:10-29

Is this a bad pattern to use with custom hooks?

I'm passing in an array and then looping over that to determine what components will be displayed.

import React from "react";
import { Image, Paragraph, Header } from "../../components/Blocks";

export const useBlocks = (blocks) => {
  const items = blocks.map((item: Item) => {
    switch (item.name) {
      case "image":
        return <Image key={item.order} data={item.data} />;
      case "paragraph":
        return <Paragraph key={item.order} data={item.data} />;
      case "heading":
        return <Header key={item.order} data={item.data} />;
      default:
        return null;
    }
  });

  return items;
};

CodePudding user response:

Using hooks to return JSX isn't a common pattern. For what you're describing a much more straightforward and more industry standard implementation would be to just create this as a component.

I extrapolated the switch logic to its own component incase there are needs to reuse this in other places of the application. Also its easier to read and test behavior this way.

import React from "react";
import { Image, Paragraph, Header } from "../../components/Blocks";

function BlockImage({item}) {
  switch (item.name) {
    case "image":
      return <Image data={item.data} />;
    case "paragraph":
      return <Paragraph data={item.data} />;
    case "heading":
      return <Header data={item.data} />;
    default:
      return null;
  }
}

export const Blocks = ({blocks}) => {
  return (
    <>
      {blocks.map((item: Item) => <BlockImage key={item.order} item={item} />}
    </>
  );
}

CodePudding user response:

By implementing this hook I can tell that you are applying Factory Pattern

Check this URL to get more details: https://refactoring.guru/design-patterns/factory-method

it's useful when it comes to loading dynamic components/classes in the runtime based on a given input. also if component creation is a little bit costly and you want to unify your solution, then it would good choice.

  • Related