Try:

var Wrapper = React.createClass({
  render: function() {
    return (
      <div className="wrapper">
        before
          {this.props.children}
        after
      </div>
    );
  }
});

See Multiple Components: Children and Type of the Children props in the docs for more info.

Answer from Sophie Alpert on Stack Overflow
Top answer
1 of 3
272

Try:

var Wrapper = React.createClass({
  render: function() {
    return (
      <div className="wrapper">
        before
          {this.props.children}
        after
      </div>
    );
  }
});

See Multiple Components: Children and Type of the Children props in the docs for more info.

2 of 3
208

Using children

const Wrapper = ({children}) => (
  <div>
    <div>header</div>
    <div>{children}</div>
    <div>footer</div>
  </div>
);

const App = ({name}) => <div>Hello {name}</div>;

const WrappedApp = ({name}) => (
  <Wrapper>
    <App name={name}/>
  </Wrapper>
);

render(<WrappedApp name="toto"/>,node);

This is also known as transclusion in Angular.

children is a special prop in React and will contain what is inside your component's tags (here <App name={name}/> is inside Wrapper, so it is the children

Note that you don't necessarily need to use children, which is unique for a component, and you can use normal props too if you want, or mix props and children:

const AppLayout = ({header,footer,children}) => (
  <div className="app">
    <div className="header">{header}</div>
    <div className="body">{children}</div>
    <div className="footer">{footer}</div>
  </div>
);

const appElement = (
  <AppLayout 
    header={<div>header</div>}
    footer={<div>footer</div>}
  >
    <div>body</div>
  </AppLayout>
);

render(appElement,node);

This is simple and fine for many usecases, and I'd recommend this for most consumer apps.


render props

It is possible to pass render functions to a component, this pattern is generally called render prop, and the children prop is often used to provide that callback.

This pattern is not really meant for layout. The wrapper component is generally used to hold and manage some state and inject it in its render functions.

Counter example:

const Counter = () => (
  <State initial={0}>
    {(val, set) => (
      <div onClick={() => set(val + 1)}>  
        clicked {val} times
      </div>
    )}
  </State>
); 

You can get even more fancy and even provide an object

<Promise promise={somePromise}>
  {{
    loading: () => <div>...</div>,
    success: (data) => <div>{data.something}</div>,
    error: (e) => <div>{e.message}</div>,
  }}
</Promise>

Note you don't necessarily need to use children, it is a matter of taste/API.

<Promise 
  promise={somePromise}
  renderLoading={() => <div>...</div>}
  renderSuccess={(data) => <div>{data.something}</div>}
  renderError={(e) => <div>{e.message}</div>}
/>

As of today, many libraries are using render props (React context, React-motion, Apollo...) because people tend to find this API more easy than HOC's. react-powerplug is a collection of simple render-prop components. react-adopt helps you do composition.


Higher-Order Components (HOC).

const wrapHOC = (WrappedComponent) => {
  class Wrapper extends React.PureComponent {
    render() {
      return (
        <div>
          <div>header</div>
          <div><WrappedComponent {...this.props}/></div>
          <div>footer</div>
        </div>
      );
    }  
  }
  return Wrapper;
}

const App = ({name}) => <div>Hello {name}</div>;

const WrappedApp = wrapHOC(App);

render(<WrappedApp name="toto"/>,node);

An Higher-Order Component / HOC is generally a function that takes a component and returns a new component.

Using an Higher-Order Component can be more performant than using children or render props, because the wrapper can have the ability to short-circuit the rendering one step ahead with shouldComponentUpdate.

Here we are using PureComponent. When re-rendering the app, if the WrappedApp name prop does not change over time, the wrapper has the ability to say "I don't need to render because props (actually, the name) are the same as before". With the children based solution above, even if the wrapper is PureComponent, it is not the case because the children element is recreated everytime the parent renders, which means the wrapper will likely always re-render, even if the wrapped component is pure. There is a babel plugin that can help mitigate this and ensure a constant children element over time.


Conclusion

Higher-Order Components can give you better performance. It's not so complicated but it certainly looks unfriendly at first.

Don't migrate your whole codebase to HOC after reading this. Just remember that on critical paths of your app you might want to use HOCs instead of runtime wrappers for performance reasons, particularly if the same wrapper is used a lot of times it's worth considering making it an HOC.

Redux used at first a runtime wrapper <Connect> and switched later to an HOC connect(options)(Comp) for performance reasons (by default, the wrapper is pure and use shouldComponentUpdate). This is the perfect illustration of what I wanted to highlight in this answer.

Note if a component has a render-prop API, it is generally easy to create a HOC on top of it, so if you are a lib author, you should write a render prop API first, and eventually offer an HOC version. This is what Apollo does with <Query> render-prop component, and the graphql HOC using it.

Personally, I use both, but when in doubt I prefer HOCs because:

  • It's more idiomatic to compose them (compose(hoc1,hoc2)(Comp)) compared to render props
  • It can give me better performances
  • I'm familiar with this style of programming

I don't hesitate to use/create HOC versions of my favorite tools:

  • React's Context.Consumer comp
  • Unstated's Subscribe
  • using graphql HOC of Apollo instead of Query render prop

In my opinion, sometimes render props make the code more readable, sometimes less... I try to use the most pragmatic solution according to the constraints I have. Sometimes readability is more important than performances, sometimes not. Choose wisely and don't bindly follow the 2018 trend of converting everything to render-props.

🌐
Medium
medium.com › @a.g.stranger › 4-different-ways-you-can-wrap-react-components-38b02302b07d
4 different ways you can wrap React components | by AhmƎd Ghrib (A.G. STRANGER) | Medium
February 12, 2023 - A Higher Order Component (HOC) is a design pattern in React that allows you to reuse logic across multiple components by wrapping a component with another component.
Discussions

how to create a wrapper that changes the props for the component in react
I m trying to do something with react components for the first time and need your help, I want to wrap a component inside another one dynamically and changing its props. More on stackoverflow.com
🌐 stackoverflow.com
how to wrap a component that can wrap other components in react?
say I have a component that can have children components like this turns out I did not create this component, it comes fr... More on stackoverflow.com
🌐 stackoverflow.com
What are your thoughts on wrapping all third party UI components with your own component to make it easy to replace libraries in the future?
I was working in a company, where we used third party UI components directly. There was a new major release of this third party library, containing multiple improvements, but also breaking changes. We wanted to upgrade to this new version, but it was impossible, as breaking changes would require to modify basically each of our components at the same time. So instead we had to first wrap each of those component with our own, refactor the whole codebase, and only then migrate. If we would wrap them from the beginning, it would be sooooo much easier. More on reddit.com
🌐 r/reactjs
137
126
July 17, 2023
How should I wrap my components with React contexts for better performance?
Doesn't really matter where the provider is located, in both cases all components that are connected via useContext will re-render - no more and no less. Implementing useMemo wherever you don't need re-renders can increase performance significantly. More on reddit.com
🌐 r/reactjs
4
3
July 12, 2023
🌐
Pluralsight
pluralsight.com › tech insights & how-to guides › tech guides & tutorials
How to Wrap One React Component into Another | Pluralsight
December 5, 2019 - However, we'll still have React Hooks. useEffect and useState can be used instead of using lifecycle methods and this.state respectively. A demonstration of improving a functional component with useState hook is shown below. It enables the wrapped component to increase the counter provided by the HOC.
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-create-wrapper-components-in-react-with-props
How To Create Wrapper Components in React with Props | DigitalOcean
May 18, 2020 - In this tutorial, you’ll create wrapper components with props using the React JavaScript library. Wrapper components are components that surround unknown components and provide a default structure to display the child components.
🌐
GitHub
github.com › compulim › react-wrap-with
GitHub - compulim/react-wrap-with: Wrap a React component in another component by Higher-Order Component.
If not every props on the container component need to be extracted or spied, the withProps HOC can help setting some of the props to a fixed value. import { withProps, wrapWith } from 'react-wrap-with'; const ThemeProvider = ({ accent, children }) => ( <ThemeContext.Provider value={{ accent }}>{children}</ThemeContext.Provider> ); const BlueThemeProvider = withProps(Theme, { accent: 'blue' }); const withBlueTheme = wrapWith(BlueThemeProvider);
Author   compulim
🌐
Codeconcisely
codeconcisely.com › posts › react-wrapper-component
Wrap a Component Inside Another in React - Code Concisely
October 23, 2022 - You can create generic container components that wrap other components like cards, modals and sidebars. To wrap a component in another component in React you have to use the built-in children prop.
🌐
DhiWise
dhiwise.com › post › designing-high-performance-uis-with-react-component-wrapper
Guide to React Component Wrapper for Optimal UI Performance
January 17, 2024 - This approach keeps your React ... scalability. A wrapper component is a React component that 'wraps' around another component or elements, providing a layer of abstraction that can manage state, props, and behavior....
Find elsewhere
🌐
DEV Community
dev.to › taiwobello › how-to-create-a-wrapper-component-in-react-29p
How to create a wrapper component in react. - DEV Community
March 15, 2022 - In this article, you will learn about a wrapper component in react, its utility, and how to make a wrapper component.
🌐
TypeOfNaN
typeofnan.dev › how-to-conditionally-wrap-jsx-with-a-component-in-react
How to conditionally wrap JSX with a component in React | TypeOfNaN
June 14, 2021 - function Wrapper(props) { if (props.showModal) { return <Modal>{props.children}</Modal>; } return props.children; } Then, we can pull this into our other component like so:
🌐
C# Corner
c-sharpcorner.com › article › what-is-a-wrapper-component-in-react
What is a Wrapper Component in React?
February 9, 2024 - You can use this WrapperComponent to wrap other components or elements, for example. import React from 'react'; import WrapperComponent from './WrapperComponent'; const App = () => { return ( <WrapperComponent> <h1>Hello, World!</h1> <p>This ...
🌐
The Web Dev
thewebdev.info › home › how to wrap one component into another with react?
How to Wrap One Component into Another with React? - The Web Dev
September 18, 2021 - To wrap one component into another with React, we add the children prop into the parent component.
🌐
Gabriele Romanato
gabrieleromanato.name › generic-wrapper-components-in-react
Generic wrapper components in React | Gabriele Romanato
In this article, we will explore how to create a generic wrapper component in React. A wrapper component is a component that wraps around another component and adds some additional functionality or styling to it.
🌐
SheCodes
shecodes.io › athena › 1967-why-should-we-wrap-react-components-in-a-div
[React] - Why Should We Wrap React Components in a ? - | SheCodes
This component should render the text Directors Page in an <h1>, and make a new <div> for each director. The <div> should contain the director's name and a <ul> with a list of their movies ... using react Inside of your ‘App’ class ‘render’ method, return a div with your basic information for example name, number, date of birth and etc.
🌐
React Bits
vasanthk.gitbooks.io › react-bits › content › ux-variations › 05.wrapper-components.html
Wrapper Components · React Bits
const SampleComponent = () => { <Wrap tagName="div" content="Hello World" /> }; const Wrap = ({ tagName, content }) => { const Tag = `${tagName}` // variable name must begin with capital letters return <Tag>{content}</Tag> } Slides from my talk: Building Multi-tenant UI with React
🌐
Stack Overflow
stackoverflow.com › questions › 57752484 › how-to-wrap-a-component-that-can-wrap-other-components-in-react
how to wrap a component that can wrap other components in react?
turns out I did not create this component, it comes from an external dependency, but I would like to use this component in various places passing the same props, for that I thought of a ParentComponent to wrap Component up. I have done that before and it worked as long as the component being wrapped does not surround other components like this one.
🌐
Reddit
reddit.com › r/reactjs › what are your thoughts on wrapping all third party ui components with your own component to make it easy to replace libraries in the future?
r/reactjs on Reddit: What are your thoughts on wrapping all third party UI components with your own component to make it easy to replace libraries in the future?
July 17, 2023 -

Hi everyone,

I'm working on a new project and we're using Material UI components. I was thinking of wrapping each component with my own and just forward the props. In the future if we want to switch from Material UI to another library I would only touch the code in the wrapper component, keeping the main pages untouched(or almost untouched).

I was discussing it with a friend and he told me it's overkill. I want to get others opinions. Is it common, good practice, issues with this approach?

🌐
SitePen
sitepen.com › blog › wrapping-web-components-with-react
Wrapping Web Components With React - SitePen
February 23, 2021 - The React wrapper needs to provide access to all of the component’s attributes and properties as props on the React component. The wrapper needs to provide a way to handle events that may be triggered by the underlying component. The wrapper needs to do its best to keep the component’s DOM in sync with React’s virtual DOM.
🌐
Reddit
reddit.com › r/reactjs › how should i wrap my components with react contexts for better performance?
r/reactjs on Reddit: How should I wrap my components with React contexts for better performance?
July 12, 2023 -

The question is simple, but I couldn't find a clear answer on web...

Which of the following approaches is more performant (causes less re-renders, etc...)?

Having one single file where I wrap every context of the application, for example: https://ibb.co/pZv1t58

Or wraping only the components that really consume from that context, for example:

https://ibb.co/7SYzJSs

🌐
Medium
medium.com › @gilfink › wrapping-react-components-inside-custom-elements-97431d1155bd
Wrapping React Components Inside Custom Elements | by Gil Fink | Medium
July 15, 2019 - Then, the function uses React’s createElement function to create the CollapsibleReact component instance. The createElement also receives the props object as a second argument and the children prop as third argument. In order to pass the children as expected I use the HTML slot element to make a bridge between the wrapping component children and the wrapped component children.