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" : ""} />
);
}
});
If you use es6, you can simply write like this.
Considering this post JSX In Depth you can solve your problem this way
Late to the party. Here is an alternative.
Or its inline version
You can use the same shortcut, which is used to add/remove (parts of) components (
{isVisible && <SomeComponent />}
).In React you can conditionally render Components but also their attributes like props, className, id, and more.
In React it's very good practice to use "Ternary operator" which can help you conditionally render Components.
Example shows also how to conditionally render Component and its style atribute
Here is simple example :
This should work, since your state will change after the ajax call, and the parent component will re-render.