{childr" /> {childr" /> {childr"/>

How do I get the individual elements that are children of a React component?

61 Views Asked by At

I have a BillBoard component like this:

const BillBoard = ({ children }) => {

return (
    <>
      <h2>Billboard</h2>
      <div className="BillBoard__frame">{children}</div>
    </>
  )
}

And I put some elements inside the BillBoard component like so:

<BillBoard>
    <video
      width="400">
      <source
        src="/videos/BigBuckBunnySample2.mp4"
        type="video/mp4"
      />
    </video>
    <img
      width="400"
      src="/images/fabien-bellanger-zKFoVBS_WGE-unsplash.jpg"
      alt="Sea view"
    />
    <p>Some random text that appears in a slide of the billboard</p>
  </BillBoard>

How do I get the elements immediately inside the BillBoard component (in this case video element, img element and p element), so that I can show them one by one inside the div.BillBoard__frame div.

2

There are 2 best solutions below

0
BetterReact Developer On BEST ANSWER

In React, you can access the individual children elements of a component using the React.Children utility functions. In your case, you can use React.Children.map to iterate over the children elements and render them inside the div.BillBoard__frame.

you can refer to this

Here's how you can achieve this:

import React from 'react';

const BillBoard = ({ children }) => {
  return (
    <>
      <h2>Billboard</h2>
      <div className="BillBoard__frame">
        {React.Children.map(children, (child, index) => (
          <div key={index} className="BillBoard__item">
            {child}
          </div>
        ))}
      </div>
    </>
  );
};

const RenderComponent = () => {
  return (
    <BillBoard>
      <video width="400">
        <source src="/videos/BigBuckBunnySample2.mp4" type="video/mp4" />
      </video>
      <img
        width="400"
        src="/images/fabien-bellanger-zKFoVBS_WGE-unsplash.jpg"
        alt="Sea view"
      />
      <p>Some random text that appears in a slide of the billboard</p>
    </BillBoard>
  );
};

export default RenderComponent;
0
C.Y. On

you can do the type of children an array of childs and the code is:

 <div className="BillBoard__frame">{children.map(child=>child)}</div>

the children is:

[ <video
      width="400">
      <source
        src="/videos/BigBuckBunnySample2.mp4"
        type="video/mp4"
      />
    </video>,
    <img
      width="400"
      src="/images/fabien-bellanger-zKFoVBS_WGE-unsplash.jpg"
      alt="Sea view"
    />,
    <p>Some random text that appears in a slide of the billboard</p>
]