I want to create a functional component that wraps other components and uses JSX in its render method. I've seen a lot of content online about how to do this with class components, but I'm curious if it works with functional components.
function WrappedContent() {
return <p>I'm wrapped</p>
}
function Wrapper(WrappedComponent) {
return (
<div>
<p>Wrapped: </p>
<WrappedComponent />
</div>
)
};
function App() {
return (
<div>
<Wrapper>
<WrappedContent />
</Wrapper>
</div>
)
}
I'm guessing it has something to do with how child components are passed into <Wrapper>
(via props.children?).
Here's a codesandbox with the above code: https://codesandbox.io/embed/gifted-cray-bqswi
(via props.children?)
Yes:
function WrappedContent() {
return <p>I'm wrapped</p>
}
function Wrapper(props) {
return (
<div>
<p>Wrapped: </p>
{props.children}
</div>
)
}
function App() {
return (
<div>
<Wrapper>
<WrappedContent />
</Wrapper>
</div>
)
}
ReactDOM.render(<App/>, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Note that Wrapper
accepts a parameter called props
, and uses props.children
. You could do it with destructuring if you don't have any other props (or even if you do, but it's a small number):
function Wrapper({children}) {
return (
<div>
<p>Wrapped: </p>
{children}
</div>
)
}
What gets passed to functional components is the props
, and child elements are contained in props.children
:
function WrappedContent() {
return <p>I'm wrapped</p>
}
function Wrapper(props) { // <-- here
return (
<div>
<p>Wrapped: </p>
{props.children} // <-- here
</div>
)
};
function App() {
return (
<div>
<Wrapper>
<WrappedContent />
</Wrapper>
</div>
)
}
https://codesandbox.io/embed/priceless-borg-brlbk
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With