openlang

TS2339 on a TSX label: React rejects the for attribute

With typescript, react, TSX source files and definitely typed declarations, compilation gives me this error:

  error TS2339: Property 'for' does not exist on type 'HTMLProps<HTMLLabelElement>'.

It happens while compiling a component containing this TSX

  <label for={this.props.fieldId} className="field-caption">{this.props.caption}</label>

I've fixed it already, but I'm posting this for whoever encounters it next because neither Google nor StackOverflow searches turned up the answer

The conversation continues 2

Follow the reasoning
  1. Permalink

    Changing the attribute from for to htmlFor fixed it

      <label htmlFor={this.props.fieldId} className="field-caption">{this.props.caption}</label>

    React itself seems to treat for specially, similarly to its handling of class (where it wants className), so the definitely typed declarations aren't the cause of this issue.

  2. Permalink

    That answer is largely right, although I'd clarify that "htmlFor" and "className" belong to JavaScript rather than being specific to React. For example, creating that kind of label with plain JavaScript could look something like this:

      const captionNode = document.createElement('label');
      captionNode.htmlFor = "field";
      captionNode.innerText = "caption";
      captionNode.className = "field-caption";

    That's probably exactly why JSX (TSX) uses "className" and "htmlFor" as well (JSX is basically syntactic shorthand for assigning each of those Javascript propeties directly yourself).

Other sides of the same question

  1. Making the sender appear as a label instead of an email address using Java Mail

    Im sending messages through the Java Mail API. On arrival, the inbox displays the address that sent the message. Id like some…

    Replies 2Latest activity java
  2. Dynamics CRM access from TypeScript

    Because my CRM code runs in a webresource, I have to write to retrieve the entity's data. Regrettably, that expression fails…

    Replies 2Latest activity typescript
  3. What date formatting does a Gleam HTTP response header need?

    I want to send a Date header. The required format looks like this: This is my current attempt:

    Replies 3Latest activity gleam