Home > Software design >  How to send multiple elements as React children and position individually where you want
How to send multiple elements as React children and position individually where you want

Time:09-12

The structure should look like this:

<Modal>
  <Header />
  <Body />
  <Footer />
</Modal>

The output should look like this

<div>
 <header>
  <Header />
 </header>
 <main>
  <Body />
 </main>
 <footer>
  <Footer />
 </footer>
</div>

CodePudding user response:

You can select the passed children by their index and position them. Here's how to achieve the solution,

const Modal = ({children}) => {

 return (
   <div>
    <header>
     { children[0] }
    </header>
    <main>
     { children[1] }
    </main>
    <footer>
     { children[2] }
    </footer>
  </div>
 )
}

CodePudding user response:

We have this option to specify different spaces for multiple components. In React, we don't but this action can be done by passing props. Like this:

<MyComponent
  headerComponent={<Header />} 
  bodyComponent={<Body />}
  footerComponent={<Footer />}
>
</div>

And in MyComponent:

const MyComponent = (props) => {
  return (
    <div>
      {props.headerComponent}

      {props.bodyComponent}

      {props.footerComponent}
    </div>
  )
}

CodePudding user response:

const Modal = ({ children }) => {
return (
<React.Fragment>
  <header>{children[0]}</header>
  <main>{children[1]}</main>
  <footer>{children[2]}</footer>
</React.Fragment>
)};

or

const Modal = ({ children }) => {
return (
<>
  <header>{children[0]}</header>
  <main>{children[1]}</main>
  <footer>{children[2]}</footer>
</>
)};

which does the same things.

  • Related