Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 945
rpechayr Avatar asked Jan 13 '15 16:01

rpechayr


1 Answers

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)
    }
});

ReactDOM.render(
  React.createElement(Container, {implComponent: SomePredefinedVariable}),
   document.getElementById('content')
);
ReactDOM.render(
  React.createElement(Container, {implComponent: "div"}),
   document.getElementById('content')
);
like image 118
Brigand Avatar answered Sep 21 '22 15:09

Brigand