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)