skip to Main Content

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

Answers


  1. 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>
    ]
    
    Login or Signup to reply.
  2. 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;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search