Malkhazi Dartsmelidze
Malkhazi Dartsmelidze

Reputation: 4992

How to wrap react children with dynamic components or tags

I want to make a Component or function to wrap given component with given parameters.

Example:

// Input
wrapComponent(ComponentToWrap, ['div', 'main', 'span']);

// Output must be equivalent to this:
<div>
  <main>
    <span>
      <ComponentToWrap />
    </span>
  </main>
</div>
// Input
wrapComponent(ComponentToWrap, ['div', 'main', SomeParentComponent]);

// Output must be equivalent to this:
<div>
  <main>
    <SomeParentComponent>
      <ComponentToWrap />
    </SomeParentComponent>
  </main>
</div>

Wrapper array can be any size 0 to 10+ ...

I didn't tried anything because I have no idea how to implement this dynamicly. Any answer will be appreciated.

Upvotes: 0

Views: 1276

Answers (1)

Yosef Tukachinsky
Yosef Tukachinsky

Reputation: 5895

Try this:

const wrapComponent = (component, wrappers) => {
  const all = [...wrappers, component];
  const create = i => {
    const C = all[i];
    if(!all[i]) return null;
    if(typeof C ==='string')
      return React.createElement(all[i], null, create(i+1));
    return <C>{create(i+1)}</C>
  }
  return create(0);
}
const Test = ({children}) => <div><h1>TEST</h1><div id="test">{children}</div></div>
const Test2 = () => <h1>I'm Here!</h1>
const MyComponent = () => <div id="wrapper">{wrapComponent(Test2, ['div', 'span', Test,'span'])}</div>

ReactDOM.render(
  <MyComponent/>,
  document.getElementById("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>

output looks like this: 1

Upvotes: 2

Related Questions