Skip to content

syntax for choosing setting a property vs attribute on elements #4416

Open
@trusktr

Description

@trusktr

Describe the feature you'd love to see

It is not possible to guess 100% of the time whether an element user needs to set a property, or an attribute.

Does this set an attribute, or a property?

return <some-element foo={[1, 2, 3]} />

Answer: it depends, sometimes Preact sets the .foo property, sometimes Preact sets the foo attribute. The user has no control over this.

The implementation of an element can vary (and may be out of the Preact user's control):

  • some elements handle properties only
  • some elements handle attributes only
  • some elements handle both
  • even if an element handles one or the other, or both
    • a user might want to set the attribute
    • or the property
    • or both
  • user might want to add or remove an attribute based on a boolean (regardless if they also want to set the corresponding JS property or not)

Design choices out of the control of Preact:

  • some element authors rely on attributes for styling :host with attribute selector
  • some element users may want to set an attribute for styling from the outside regardless if the element accepts a JS property (they could set the JS prop, and the element would work, but their CSS would not be able to select the element)
  • etc

It is not possible for Preact to always guess correctly which of the above cases the user will want, and the Preact user needs control.

Additional context (optional)

Users need a way to express whether they want to set an attribute, or a property, or both. We also need to be able to add/remove attributes based on booleans.

Lit, Solid.js, and others have (sometimes only partial) solutions to this. For more details on the solutions other frameworks have, see this new test proposal for custom-elements-everywhere:

Possible solution idea

Solid.js has JSX syntax such as attr:foo=... and prop:foo=... for setting an attribute vs a property, but no boolean support. Pota, a library that is built on Solid.js, has its own JSX and html syntax that adds bool:foo=... support. Etc.

Preact could choose to adopt a similar approach, which is valid JSX syntax.

An alternative html template string tag for Preact could also provide Lit-like syntax (.foo=..., foo=..., and ?foo=...).

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions