How do I conditionally add attributes to React components?
Is there a way to only add attributes to a React component if a certain condition is met?
I'm supposed to add required and readOnly attributes to form elements based on an Ajax call after render, but I can't see how to solve this since readOnly="false"
is not the same as omitting the attribute completely.
The example below should explain what I want, but it doesn't work.
(Parse Error: Unexpected identifier)
var React = require('React');
var MyOwnInput = React.createClass({
render: function () {
return (
<div>
<input type="text" onChange={this.changeValue} value={this.getValue()} name={this.props.name}/>
</div>
);
}
});
module.exports = React.createClass({
getInitialState: function () {
return {
isRequired: false
}
},
componentDidMount: function () {
this.setState({
isRequired: true
});
},
render: function () {
var isRequired = this.state.isRequired;
return (
<MyOwnInput name="test" {isRequired ? "required" : ""} />
);
}
});