snippetjavascriptreactCritical
How do I conditionally add attributes to React components?
Viewed 0 times
conditionallyhowaddreactattributescomponents
Problem
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
The example below should explain what I want, but it doesn't work.
(Parse Error: Unexpected identifier)
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
}
Solution
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.
const InputComponent = function() {
const required = true;
const 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.
Code Snippets
const InputComponent = function() {
const required = true;
const disabled = false;
return (
<input type="text" disabled={disabled} required={required} />
);
}<input type="text" required>Context
Stack Overflow Q#31163693, score: 923
Revisions (0)
No revisions yet.