Boolean element attributes (disabled, checked, etc.) in JSX
See original GitHub issueThis is how I’ve been conditionally putting the disabled
attribute on elements, with a boolean variable:
<input disabled={isDisabled} type=... />
When isDisabled
is falsey, the attribute won’t be output. When true, it will output the following, which works in browsers but is against the HTML5 spec:
<input disabled="true" type=... />
I could get in line with the spec by setting disabled="disabled"
on the element, but that requires a ternary operation instead of a simple boolean:
<input disabled={isDisabled ? "disabled" : false} ... />
Ideally, my current bit of JSX (at the top of this issue) would output this HTML, assuming disabled
is set to true:
<input disabled type=... />
More generally, if a known boolean attribute gets assigned a variable set to true
as in my example, JSX should output just the attribute as per the HTML5 spec.
Issue Analytics
- State:
- Created 10 years ago
- Reactions:15
- Comments:21 (9 by maintainers)
Top Results From Across the Web
React: setting the disabled attribute based on a state
You can set disabled property through boolean value, like this <button type="button" disabled={this.state.submitting} onClick={this.
Read more >HTML disabled Attribute - W3Schools
The disabled attribute is a boolean attribute. When present, it specifies that the element should be disabled. A disabled element is unusable. The...
Read more >HTML attribute: disabled - HTML: HyperText Markup Language
The Boolean disabled attribute, when present, makes the element not mutable, focusable, or even submitted with the form.
Read more >Documentation - SolidJS · Reactive Javascript Library
import { Show } from "solid-js"; function Show<T>(props: { when: T | undefined | null | false; keyed: boolean; fallback?: JSX.Element; children: JSX.Element...
Read more >Attributes | Block Editor Handbook
The only exception is when checking for the existence of an attribute (for example, the disabled attribute on a button ). In that...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
For those who are looking for work-arounds, for the time being, I found this on StackOverflow.
You should not write CSS selectors like
[checked]
. This is just a wrong way to approach the problem. Browser doesn’t guarantee that attributes stay synced with properties.In your example, instead of
you should use
:checked
pseudoclass:Then it works with expected when toggled through JS (including React).