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


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>

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


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.


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:


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".


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.


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


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>.


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.