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 won't work (Parse Error: Unexpected identifier).
var React = require('React');
var MyOwnInput = React.createClass({
render: function () {
return (
);
}
});
module.exports = React.createClass({
getInitialState: function () {
return {
isRequired: false
}
},
componentDidMount: function () {
this.setState({
isRequired: true
});
},
render: function () {
var isRequired = this.state.isRequired;
return (
);
}
});
Answer
Apparently, for certain attributes, React is intelligent enough to omit the attribute if the value you pass to it is not truthy. For example:
var InputComponent = React.createClass({
render: function() {
var required = true;
var disabled = false;
return (
);
}
});
will result in:
Update: if anyone is curious as to how/why this happens, you can find details in ReactDOM's source code, specifically at lines 30 and 167 of the DOMProperty.js file.
No comments:
Post a Comment