0

This following code actualy works, but I wonder if it's a good practice or not. Because to me, it sounds like I breaking the rules. But I dont see other ways to do what I want. And I want to render 2 lists build with the same logic but that render different types of items. If you know a better way to do this tell me how.

function App() {
  const data = [1, 2, 3];
  return (
    <>
      <ItemList ItemComponent={BlueItem} data={data} />
      <ItemList ItemComponent={RedItem} data={data} />
    </>
  );
}

function ItemList({ ItemComponent, data }) {
  return (
    <ul>
      {data.map((value) => {
        return <ItemComponent value={value} />;
      })}
    </ul>
  );
}

function BlueItem({ value }) {
  return (
    <li className="BlueItem" /* + specifics attributes for BlueItem */>
      {value}
    </li>
  );
}

function RedItem({ value }) {
  return (
    <li className="RedItem" /* + specifics attributes for RedItem */>
      {value}
    </li>
  );
}

Update : For more details, this is actualy a simplified example. In my realworld code the BlueItem and RedItem are much more complicated. They have serveral specific sub components, states logic, events listening etc... This is why I dont just use a generic Item component and set this props.

foxwit
  • 315
  • 2
  • 6
  • For working code, try https://codereview.stackexchange.com/ – jmargolisvt Nov 25 '21 at 00:54
  • It's a perfectly valid pattern, and one that makes use of composable interfaces. If you use TypeScript you can codify and help enforce that. If you end up with too many individual components (subjective), that's when you would want to consider consolidating and refactoring things a bit (can make it easier to test). It can be overkill if you're only alternating a couple props (eg className) based on a set of enumerated values; in that case you'd want to define that enum and make a prop that uses that, setting the className and/or other props based on that. – Derek Nov 25 '21 at 08:42
  • @jmargolisvt Sorry for the wrong place of this post. I'll do better next time. – foxwit Nov 26 '21 at 11:15
  • @Derek Thanks a lot for your explanation. It's make me more confidente about my code structure. – foxwit Nov 26 '21 at 11:21

1 Answers1

0

Looks like its fine if BlueItem and RedItem both have specific attributes and difficult to handle out of the component. See below example of React Router

function App() {
    return (
        <main>
            <Switch>
                <Route path="/" component={Home} exact />
                <Route path="/about" component={About} />
                <Route path="/shop" component={Shop} />
            </Switch>
        </main>
    )
}

If attributes are simple it will be good to keep them outside as objects and pass as props and use spread operator

J-007
  • 206
  • 2
  • 10