The React “Children” prop

Jeff P
1 min readJan 11, 2024

--

Unlike custom props, the “children” prop is a special reserved prop to pass down, and it is used to pass down whatever is held between the opening and closing tags of the component.

So for example, if we had the following code:

  return (
<>
<button className="close" onClick={() => setIsOpen(!isOpen)}>
X
</button>
{isOpen && (
<div className="steps">
<div className="numbers">
<div className={step === 1 ? "active" : ""}>1</div>
<div className={step === 2 ? "active" : ""}>2</div>
<div className={step === 3 ? "active" : ""}>3</div>
</div>

<p className="message">
Step {step}: {messages[step - 1]}
</p>
<div className="buttons">
<Button onClick={handlePrevious}>Previous</Button>
<Button onClick={handleNext}>Next</Button>
</div>
</div>
)}
</>
);

the data being passed onto the Button components from “children” would be:

Previous
Next

As these are what are between the opening and closing tags.

So you could pass down “children” into the component like this:

function Button({ onClick, children }) {
return (
<button
style={{ backgroundColor: "#7950f2", color: "#fff" }}
onClick={onClick}
>
{children}
</button>
);
}

And therefore the Button would show the text “Previous” and “Next”

--

--

Jeff P
Jeff P

Written by Jeff P

I tend to write about anything I find interesting. There’s not much more to it than that really :-)

No responses yet