Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically Rendering a React component

In React JSX it does not appear to be possible to do something like this:

render: function() {    return (      <{this.props.component.slug} className='text'>        {this.props.component.value}      </{this.props.component.slug}>    );  }

I get a parse error: Unexpected token {. Is this not something React can handle?

I'm designing this component so that under the hood, the values stored in this.props.component.slug will contain valid HTML elements (h1, p, etc.). Is there any way to make this work?

like image 898
eriklharper Avatar asked Oct 22 '14 23:10

eriklharper


People also ask

How do I render component dynamically in React?

Dynamic component rendering with React To allow us to render a JSON by dynamic components using their name we first have to loop through the array of components itself. Below you can see that we're using the map function to do exactly that.

What is dynamic component in React?

As the building blocks of React applications, components are dynamic, in that they can describe a template of HTML and fill in variable data. This lesson builds a real example of a blogging application to illustrate dynamic components.

How do you render a component dynamically based on a JSON?

To render the components based on the component key in the JSON config, we first need to create an object that maps the components with the component key. As you can see, I have mapped the component key with the corresponding Reactstrap component. At the top, we will import all the required components.


1 Answers

You should not put component slug in curly braces:

var Hello = React.createClass({     render: function() {         return <this.props.component.slug className='text'>             {this.props.component.value}         </this.props.component.slug>;     } });  React.renderComponent(<Hello component={{slug:React.DOM.div, value:'This is my header'}} />, document.body); 

Here is a working fiddle: http://jsfiddle.net/kb3gN/6668/

Also, you can find JSX Compiler helpful for debugging these kind of errors: http://facebook.github.io/react/jsx-compiler.html

like image 96
nilgun Avatar answered Oct 26 '22 17:10

nilgun