How to select between different child components, depending on code higher up?

Viewed 32

Below is a component for a List/<ul> where there is a <li> for each item in classesByName. Is there any way to decide between using the component <ClassItemAnchor /> and an alternative, say <ClassItemButton /> depending on code higher up (outside of <ClassList />)? Otherwise, I'd have to create a new <ul> component to have a different <li> component?

import ClassItemAnchor from "./ClassItemAnchor"

const ClassList = ({ classesByName, getChat, searchName }) => {

    return (
        <ul className="chat-list">
            {classesByName.map((Class) => (
                <ClassItemAnchor
                    key={Class.id}
                    Class={Class}
                    searchName={searchName}
                    getChat={getChat}
                />
            ))}
        </ul>
    )
}

export default ClassList

Thank you

1 Answers

You can pass a prop named isAnchor (Boolean) from parent to conditionally render the ClassItemAnchor and ClassItemButton.

const ClassList = ({ classesByName, getChat, searchName, isAnchor = true }) => {
  return (
    <ul className="chat-list">
      {classesByName.map((Class) =>
        isAnchor ? (
          <ClassItemAnchor
            key={Class.id}
            Class={Class}
            searchName={searchName}
            getChat={getChat}
          />
        ) : (
          <ClassItemButton
            key={Class.id}
            Class={Class}
            searchName={searchName}
            getChat={getChat}
          />
        )
      )}
    </ul>
  );
};

if isAnchor is true , it will render ClassItemAnchor else ClassItemButton

Usage

<ClassList isAnchor={true}/>
Related