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!
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})
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With