Am I using React.cloneElement wrong? (deprecation warning)


#1

Not sure what’s up with this warning:

Warning: Template1.type is deprecated. Use Template1 directly to access the class.

Container = React.createClass({
  displayName: 'Container',

  render() {
    const componentName = 'Template1';
    const content = React.cloneElement(window[componentName]);

    return <div>
      {content}
    </div>
  }
});

Is there a better way to take a component name as a string and render it out?


#2

Ah, the solution is:

Container = React.createClass({
  displayName: 'Container',

  render() {
    const component = window['Template1'];
    return React.createElement(component);
  }
});

I’m not 100% clear on when to use cloneElement or createElement.


#3

If you want a clean new element, without existing props, use createElement. If you want a copy of some element with his props, use cloneElement. :wink:


#4

Well yes, obviously one creates and one clones. :slight_smile: They take different arguments though, and I couldn’t figure out if I was supposed to pass in <Template1 /> or Template1 or "Template1".


#5

From the docs you can see, that in React.createElement you can pass string/ReactClass ('Template' / Template) and in React.cloneElement you can pass ReactElement (<Template>).

The props will be also handled differently, createElement will have only that you define and cloneElement will have the props from the cloned element + new props.


#6

Actually, strangely enough, React.createElement('Template1') did not work.


#7

You need to read the docs better, below it is explained, why it is so. If you pass string 'Template', it will create you an element <template></template>.


#8

I didn’t see anything about that, just this:

Create and return a new ReactElement of the given type. The type argument can be either an html tag name string (eg. ‘div’, ‘span’, etc), or a ReactClass (created via React.createClass).

I suppose if you pass a string, it has to be a known HTML tag.