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 (
<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" : ""} />
);
}
});
Apparently, for certain attributes, React is intelligent enough to omit the attribute if the value you pass to it is not truthy. For example:
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.
Here's a way I do it.
with Conditional:
I still prefer using the regular way of passing props down because it is more readable (in my opinion) in the case of not have any conditionals.
with No conditional:
Here is an example of using Bootstrap's
Button
via React-Bootstrap (version: 0.32.4).Depending on the condition, either
{bsStyle: 'success'}
or{}
will be returned. The spread operator will then spread the properties of the returned object toButton
component. In the falsy case, since no properties exist on the returned object, nothing will be passed to the component.Alternative way based on @Andy Polhill's comment below:
The only small difference is that in the 2nd example inner component
<Button/>
'sprops
object will have a keybsStyle
with value ofundefined
.Just throwing another option out there, but @juandemarco's answer is usually correct.
Build an object how you like:
Render with spread, optionally passing other props also.
Late to the party.
Lets say we want to add a custom property (using aria-* or data-*) if a condition is true:
Lets say we want to add a style property if a condition is true: