clrux clrux - 13 days ago 7
React JSX Question

How to include form field attributes based on state in React?

I am trying to make an accessible form in React and I need to toggle the attribute

based on the state of the field (i.e., if it has an error associated with it).

I know how to toggle the value of the attribute, but with regards to WCAG, a present but empty attribute of this type will fail. The entire attribute needs to be fully present or fully absent. Anything I try in-line throws errors and breaks the render.

To give an example, this is what I've been trying:

<input type="text" name="someName" ref="someRef" {!this.state.isValid ? aria-describedby="helperText" : ''} required />
<p id="helperText">Helper text for this form field.</p>

Again though, an empty attribute value for
is invalid.

Is there any way to acheive this?


Just spread it like this:

<input type="text" 
     {... !this.state.isValid && {'aria-describedby': 'helperText'} } 
     required />

This is basically spread operator usage.