rpechayr rpechayr - 1 month ago 6
React JSX Question

React render component using its name

I am experimenting React.js and it is working really well. I am wondering if it is possible to inject classes to other classes like so:

var Container = React.createClass({
render: function() {
<{this.props.implComponent}/>
}
});


Assuming implComponent has been passed like so:

React.render(
<Container implComponent="somePredefinedVariable" />,
document.getElementById('content')
);


This does not work because of a Syntax error. I can easily understand why.

In other words I'd like to inject classes to other classes based on names. Is this possible? How can I do that?

Answer

You were close. You need to pass the component class it self (not a string), and then because the tag syntax takes a variable already, you get rid of the {}s. Also don't forget to return the node from render.

var Container = React.createClass({
    render: function() {
        return <this.props.implComponent />
    }
});

React.render(
  <Container implComponent={SomePredefinedVariable} />,
   document.getElementById('content')
);

If you want to pass a basic dom component, you'd use a string

This makes sense if you think about the transform result

var Container = React.createClass({displayName: "Container",
    render: function() {
      return React.createElement(this.props.implComponent, null)
    }
});

React.render(
  React.createElement(Container, {implComponent: SomePredefinedVariable}),
   document.getElementById('content')
);
React.render(
  React.createElement(Container, {implComponent: "div"}),
   document.getElementById('content')
);