Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping functional JSX components with other functions

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

like image 925
labarna Avatar asked Sep 12 '25 13:09

labarna


2 Answers

(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>
  )
}
like image 161
T.J. Crowder Avatar answered Sep 14 '25 03:09

T.J. Crowder


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

like image 28
rossipedia Avatar answered Sep 14 '25 04:09

rossipedia