Monday, May 21, 2018

javascript - 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 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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...