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)
function MyInput({isRequired}) { return <input classname="foo" {isRequired ? "required" : ""} /> }
By using spread attributes, you can dynamically add (or override) whatever attributes you'd like by using a javascript object instance. In my example above, the code creates a disabled key (with a disabled value in this case) when the disabled property is passed to the Hello component instance.
To set a data attribute on an element in React, set the attribute directly on the element, e.g. <button data-test-id="my-btn"> or use the setAttribute() method, e.g. el. setAttribute('data-foo', 'bar') . You can access the element on the event object or using a ref . Copied!
We can embed any JavaScript expression in JSX by wrapping it in curly braces. But only expressions not statements, means directly we can not put any statement (if-else/switch/for) inside JSX.
juandemarco's answer is usually correct, but here is another option.
Build an object how you like:
var inputProps = { value: 'foo', onChange: this.handleChange }; if (condition) inputProps.disabled = true;
Render with spread, optionally passing other props also.
<input value="this is overridden by inputProps" {...inputProps} onChange={overridesInputProps} />
Apparently, for certain attributes, React is intelligent enough to omit the attribute if the value you pass to it is not truthy. For example:
const InputComponent = function() { const required = true; const disabled = false; return ( <input type="text" disabled={disabled} required={required} /> ); }
will result in:
<input type="text" required>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With