Sometimes, we want to wrap one component into another with React.
In this article, we’ll look at how to wrap one component into another with React.
Wrap One Component into Another with React
To wrap one component into another with React, we add the children
prop into the parent component.
For instance, we write:
import React from "react";
const Wrapper = ({ children }) => (
<div>
<div>header</div>
<div>{children}</div>
<div>footer</div>
</div>
);
const Child = ({ name }) => <div>Hello {name}</div>;
export default function App() {
return (
<Wrapper>
<Child name="foo" />
</Wrapper>
);
}
We create the Wrapper
component that accepts the children
prop.
And we put children
in a div.
Next, we create the Child
component that takes the name
prop and renders some text.
In App
, we wrap Wrapper
around Child
so that Child
is set as a value in the children
array.
Therefore, we see:
header
Hello foo
footer
rendered.
Conclusion
To wrap one component into another with React, we add the children
prop into the parent component.