Skip to content

[lit-html] ref() directive should accept undefined #3965

@justinfagnani

Description

@justinfagnani

Should this be an RFC?

  • This is not a substantial change

Which package is this a feature request for?

Lit Core (lit / lit-html / lit-element / reactive-element)

Description

Sometimes a ref object may be optional, especially if it's an external property. In these cases it would be very useful to let ref() accept undefined and just do nothing.

Example:

class MyElement extends LitElement {
  /**
   * Pass a Ref object to receive a reference to the "foo" div
   */
  @property({attribute: false})
  fooRef?: Ref<HTMLDivElement>;
  
  render() {
    return html`<div ${ref(this.fooRef}}></div>`;
  }
}

This example currently gives us a type error at ref(this.fooRef}, since this.fooRef may be undefined.

Alternatives and Workarounds

We can make an orphan ref:

html`<div ${ref(this.fooRef ?? createRef()}}></div>`;

But that's very ugly.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

Status

✅ Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions