Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js: Set Prop only when condition is true

I'm quite new to react.js and have some troubles passing props to children. I want to do something like this:

render: function(){
   var idProp = this.props.id ? 'id={this.props.id}' : null;
   return (
     <div {idProp} />
   );
}

So the prop id should only be passed if a condition is true. But the above code is not working. Is this possible? What am I doing wrong? Thanks!

like image 807
ilse2005 Avatar asked Apr 01 '26 18:04

ilse2005


1 Answers

var idProp = this.props.id ? 'id={this.props.id}' : null; in your code should be written in javascript way. Also you have to move "id=" to the JSX syntax.

render: function(){
   var idProp = this.props.id ? this.props.id : null;
   return (
     <div id={idProp} />
   );
}

The JSX compiler converts the code to pure js first. To create dom elements, it uses the React.createElement(...) function. To identify the parameters for the function, the JSX compiler needs attribute names of the element to be static. The converted javascript of the above code will be..

render: function(){
   var idProp = this.props.id ? this.props.id : null;
   return (
     React.createElement("div", {id: idProp})
   );
}
like image 178
Sampath Liyanage Avatar answered Apr 04 '26 06:04

Sampath Liyanage



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!