DEV Community

Cover image for Position props.children in an unique way
Sajjat Hossain
Sajjat Hossain

Posted on • Edited on

4 3

Position props.children in an unique way

Recently I faced an interesting issue. I was asked if there's any way to position each children element passed into a children component via wrapping these elements/components using a component. The syntax of the question is as follows,

Let's assume we have a modal component. So, it will be like,

Fig: 1

<Modal>
  <Header />
  <Body />
  <Footer />
</Modal>
Enter fullscreen mode Exit fullscreen mode

Now, the expected output should look similar to this codes' output,
(inside modal component)

Fig: 2

<div>
 <header>
  <Header />
 </header>
 <main>
  <Body />
 </main>
 <footer>
  <Footer />
 </footer>
</div>
Enter fullscreen mode Exit fullscreen mode

Now, here's how I solved the issue,
I did not know how to solve it as I had no experience such like this. But I thought that if I could select them via the index, I could do so. So I spun up a Next.js application and tested my theory later on. And voila! I was right. You can achieve the same output (similar to the Fig: 2) as shown here,

Fig: 3

const Modal = ({children}) => {

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

similarly:

const Modal = ({children}) => {
/**
* @desc assigning each array element to a variable;
*/
 const [header, body, footer] = children;

 return (
   <div>
    <header>
     { header }
    </header>
    <main>
     { body }
    </main>
    <footer>
     { footer }
    </footer>
  </div>
 )
}
Enter fullscreen mode Exit fullscreen mode

Maybe, it's not the best way to pass an element or achieve such output. But it's an unique way and you never know, there might be an use-case for this. Here's an working demo: Click here!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay