DEV Community

Cover image for {children} in React...?
_Khojiakbar_
_Khojiakbar_

Posted on

{children} in React...?

Imagine a Magic Hat

Imagine you have a magic hat. You can put anything you want into this hat, and it will keep those things safe and sound.

  1. The Magic Hat: This is your React component.
  2. Things in the Hat: These are the children you put inside the component.

Step 1: Create the Magic Hat Component

First, let's create a component called MagicHat (the magic hat):

const MagicHat = ({ children }) => {
    return (
        <div className="magic-hat">
            {children}
        </div>
    );
};

export default MagicHat;
Enter fullscreen mode Exit fullscreen mode

The MagicHat component is like the magic hat. It accepts a special prop called children which represents whatever you put inside the tags.

2. Step: Use the Magic Hat Component

Now, let's put some magical items (other components or elements) into the hat:

import MagicHat from './MagicHat';

const MagicShow = () => {
    return (
        <MagicHat>
            <div className="item">🐰 Bunny</div>
            <div className="item">🎩 Hat</div>
            <div className="item">🌟 Sparkle</div>
        </MagicHat>
    );
};

export default MagicShow;
Enter fullscreen mode Exit fullscreen mode

The MagicShow component uses the MagicHat component and puts three magical items inside it: a bunny, a hat, and a sparkle.

What's Happening?

When the MagicShow component is rendered, it creates this structure:

<div className="magic-hat">
    <div className="item">🐰 Bunny</div>
    <div className="item">🎩 Hat</div>
    <div className="item">🌟 Sparkle</div>
</div>
Enter fullscreen mode Exit fullscreen mode

The MagicHat component wraps around all the items, just like how a magic hat holds all the magical items.

Recap

MagicHat Component: The magic hat that holds everything.
children Prop: The magical items that are placed inside the hat.
MagicShow Component: The component that puts magical items inside the hat.

Top comments (0)

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

πŸ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay