ReactJs: How can I optimally pass a list of conditional children to parent?

21 Views Asked by At

I am trying to create a component that will be able to accept a variable number of child elements and then conditionally show each based on a state value. Let's start with a simple component that conditionally shows its children based on a button:

const Parent = () => {
  const [activeChild, setActiveChild] = useState(0);
  
  return (
    <div>
      {
        activeChild === 0 ? <Child1 />
        : activeChild === 1 ? <Child2 />
        : activeChild === 2 ? <Child3 />
        : null
      }
      <button onClick={() => setActiveChild(activeChild + 1)}
    </div>  
  )
}

Simple. Now let's say that I want to abstract it out so that this can be re-used with a variable number of children:

const App = () => {
  return (
    <>
      <Parent childList={[<Child1 />, <Child2 />, <Child3 />]} />
      <Parent childList={[<Child4 />, <Child5 />]} />
    </>
  )
}

const Parent = ({ childList: React.ReactNode[] }) => {
  const [activeChild, setActiveChild] = useState(0);
  
  return (
    <div>
      {
        childList.map((child, index) => index === activeChild && child)
      }
      <button onClick={() => setActiveChild(activeChild + 1)}
    </div>  
  )
}

My question is, if you pass in components via props like above, do they all technically render? And if so, what is the optimal way to handle this situation? Ideally, I would want only the 2 children that are supposed to be visible to render, but I'm worried that all 5 will render.

1

There are 1 best solutions below

0
Jason Ming On

You should use find or filter instead of map here.

childList.map((child, index) => index === activeChild && child)