Wrap a compoenent with mulitple parents from array

Viewed 31

Is there a way to wrap a component with multiple parents passed from an array?

Is this something a HOC would be able to handle?

const WrapperComponent = props => {

    const wrappers = [ComponentA, ComponentB, ComponentC];

    // Should return something like:
    // return (
    //    <ComponentA><ComponentB><ComponentC>
    //         {props.children}
    //    </ComponentC></ComponentB></ComponentA>
    // );
}
1 Answers

You could use reduceRight method that will start from the last element which will be the inner-most component and also set accumulator value as the component that you pass to your HOC function.

const ComponentA = ({ children }) => <div className="component-a">{children}</div>;
const ComponentB = ({ children }) => <div className="component-b">{children}</div>;
const ComponentC = ({ children }) => <div className="component-c">{children}</div>;

const WrapperComponent = (ChildComponent) => {
  const wrappers = [ComponentA, ComponentB, ComponentC];

  return wrappers.reduceRight((Prev, Component) => {
    return <Component>{Prev}</Component>
  }, <ChildComponent/> )
}

const MyComponent = () => <div> My component </div>
const App = () => WrapperComponent(MyComponent)

ReactDOM.render( <App/> , document.querySelector("#app"))
<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>
<div id="app"></div>

Related