Search code examples
reactjscomponentscompositionopen-closed-principle

Is a good practice to create a new React element based on props?


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.


Solution

  • 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