facebook / react

The library for web and native user interfaces.
https://react.dev
MIT License
225.04k stars 45.89k forks source link

RFC: Plan for custom element attributes/properties in React 19 #11347

Open robdodson opened 6 years ago

robdodson commented 6 years ago

This is meant to address #7249. The doc outlines the pros and cons of various approaches React could use to handle attributes and properties on custom elements.

TOC/Summary

Background

When React tries to pass data to a custom element it always does so using HTML attributes.

<x-foo bar={baz}> // same as setAttribute('bar', baz)

Because attributes must be serialized to strings, this approach creates problems when the data being passed is an object or array. In that scenario, we end up with something like:

<x-foo bar="[object Object]">

The workaround for this is to use a ref to manually set the property.

<x-foo ref={el => el.bar = baz}>

This workaround feels a bit unnecessary as the majority of custom elements being shipped today are written with libraries which automatically generate JavaScript properties that back all of their exposed attributes. And anyone hand-authoring a vanilla custom element is encouraged to follow this practice as well. We'd like to ideally see runtime communication with custom elements in React use JavaScript properties by default.

This doc outlines a few proposals for how React could be updated to make this happen.

Proposals

Option 1: Only set properties

Rather than try to decide if a property or attribute should be set, React could always set properties on custom elements. React would NOT check to see if the property exists on the element beforehand.

Example:

<x-foo bar={baz}>

The above code would result in React setting the .bar property of the x-foo element equal to the value of baz.

For camelCased property names, React could use the same style it uses today for properties like tabIndex.

<x-foo squidInk={pasta}> // sets .squidInk = pasta

Pros

Easy to understand/implement

This model is simple, explicit, and dovetails with React’s "JavaScript-centric API to the DOM".

Any element created with libraries like Polymer or Skate will automatically generate properties to back their exposed attributes. These elements should all "just work" with the above approach. Developers hand-authoring vanilla components are encouraged to back attributes with properties as that mirrors how modern (i.e. not oddballs like <input>) HTML5 elements (<video>, <audio>, etc.) have been implemented.

Avoids conflict with future global attributes

When React sets an attribute on a custom element there’s always the risk that a future version of HTML will ship a similarly named attribute and break things. This concern was discussed with spec authors but there is no clear solution to the problem. Avoiding attributes entirely (except when a developer explicitly sets one using ref) may sidestep this issue until the browsers come up with a better solution.

Takes advantage of custom element "upgrade"

Custom elements can be lazily upgraded on the page and some PRPL patterns rely on this technique. During the upgrade process, a custom element can access the properties passed to it by React—even if those properties were set before the definition loaded—and use them to render initial state.

Custom elements treated like any other React component

When React components pass data to one another they already use properties. This would just make custom elements behave the same way.

Cons

Possibly a breaking change

If a developer has been hand-authoring vanilla custom elements which only have an attributes API, then they will need to update their code or their app will break. The fix would be to use a ref to set the attribute (explained below).

Need ref to set attribute

By changing the behavior so properties are preferred, it means developers will need to use a ref in order to explicitly set an attribute on a custom element.

<custom-element ref={el => el.setAttribute('my-attr', val)} />

This is just a reversal of the current behavior where developers need a ref in order to set a property. Since developers should rarely need to set attributes on custom elements, this seems like a reasonable trade-off.

Not clear how server-side rendering would work

It's not clear how this model would map to server-side rendering custom elements. React could assume that the properties map to similarly named attributes and attempt to set those on the server, but this is far from bulletproof and would possibly require a heuristic for things like camelCased properties -> dash-cased attributes.

Option 2: Properties-if-available

At runtime React could attempt to detect if a property is present on a custom element. If the property is present React will use it, otherwise it will fallback to setting an attribute. This is the model Preact uses to deal with custom elements.

Pseudocode implementation:

if (propName in element) {
  element[propName] = value;
} else {
  element.setAttribute(propName.toLowerCase(), value);
}

Possible steps:

Pros

Non-breaking change

It is possible to create a custom element that only uses attributes as its interface. This authoring style is NOT encouraged, but it may happen regardless. If a custom element author is relying on this behavior then this change would be non-breaking for them.

Cons

Developers need to understand the heuristic

Developers might be confused when React sets an attribute instead of a property depending on how they’ve chosen to load their element.

Falling back to attributes may conflict with future globals

Sebastian raised a concern that using in to check for the existence of a property on a custom element might accidentally detect a property on the superclass (HTMLElement).

There are also other potential conflicts with global attributes discussed previously in this doc.

Option 3: Differentiate properties with a sigil

React could continue setting attributes on custom elements, but provide a sigil that developers could use to explicitly set properties instead. This is similar to the approach used by Glimmer.js.

Glimmer example:

<custom-img @src="corgi.jpg" @hiResSrc="corgi@2x.jpg" width="100%">

In the above example, the @ sigil indicates that src and hiResSrc should pass data to the custom element using properties, and width should be serialized to an attribute string.

Because React components already pass data to one another using properties, there would be no need for them to use the sigil (although it would work if they did, it would just be redundant). Instead, it would primarily be used as an explicit instruction to pass data to a custom element using JavaScript properties.

h/t to @developit of Preact for suggesting this approach :)

Pros

Non-breaking change that developers can opt-in to

All pre-existing React + custom element apps would continue to work exactly as they have. Developers could choose if they wanted to update their code to use the new sigil style.

Similar to how other libraries handle attributes/properties

Similar to Glimmer, both Angular and Vue use modifiers to differentiate between attributes and properties.

Vue example:

<!-- Vue will serialize `foo` to an attribute string, and set `squid` using a JavaScript property -->
<custom-element :foo="bar” :squid.prop=”ink”>

Angular example:

<!-- Angular will serialize `foo` to an attribute string, and set `squid` using a JavaScript property -->
<custom-element [attr.foo]="bar” [squid]=”ink”>

The system is explicit

Developers can tell React exactly what they want instead of relying on a heuristic like the properties-if-available approach.

Cons

It’s new syntax

Developers need to be taught how to use it and it needs to be thoroughly tested to make sure it is backwards compatible.

Not clear how server-side rendering would work

Should the sigil switch to using a similarly named attribute?

Option 4: Add an attributes object

React could add additional syntax which lets authors explicitly pass data as attributes. If developers do not use this attributes object, then their data will be passed using JavaScript properties.

Example:

const bar = 'baz';
const hello = 'World';
const width = '100%';
const ReactElement = <Test
  foo={bar} // uses JavaScript property
  attrs={{ hello, width }} // serialized to attributes
/>;

This idea was originally proposed by @treshugart, author of Skate.js, and is implemented in the val library.

Pros

The system is explicit

Developers can tell React exactly what they want instead of relying on a heuristic like the properties-if-available approach.

Extending syntax may also solve issues with event handling

Note: This is outside the scope of this document but maybe worth mentioning :)

Issue #7901 requests that React bypass its synthetic event system when declarative event handlers are added to custom elements. Because custom element event names are arbitrary strings, it means they can be capitalized in any fashion. To bypass the synthetic event system today will also mean needing to come up with a heuristic for mapping event names from JSX to addEventListener.

// should this listen for: 'foobar', 'FooBar', or 'fooBar'?
onFooBar={handleFooBar}

However, if the syntax is extended to allow attributes it could also be extended to allow events as well:

const bar = 'baz';
const hello = 'World';
const SquidChanged = e => console.log('yo');
const ReactElement = <Test
  foo={bar}
  attrs={{ hello }}
  events={{ SquidChanged}} // addEventListener('SquidChanged', …)
/>;

In this model the variable name is used as the event name. No heuristic is needed.

Cons

It’s new syntax

Developers need to be taught how to use it and it needs to be thoroughly tested to make sure it is backwards compatible.

It may be a breaking change

If any components already rely on properties named attrs or events, it could break them.

It may be a larger change than any of the previous proposals

For React 17 it may be easier to make an incremental change (like one of the previous proposals) and position this proposal as something to take under consideration for a later, bigger refactor.

Option 5: An API for consuming custom elements

This proposal was offered by @sophiebits and @gaearon from the React team

React could create a new API for consuming custom elements that maps the element’s behavior with a configuration object.

Pseudocode example:

const XFoo = ReactDOM.createCustomElementType({
  element: ‘x-foo’,
  ‘my-attr’: // something that tells React what to do with it
  someRichDataProp: // something that tells React what to do with it
});

The above code returns a proxy component, XFoo that knows how to pass data to a custom element depending on the configuration you provide. You would use this proxy component in your app instead of using the custom element directly.

Example usage:

<XFoo someRichDataProp={...} />

Pros

The system is explicit

Developers can tell React the exact behavior they want.

Non-breaking change

Developers can opt-in to using the object or continue using the current system.

Idiomatic to React

This change doesn’t require new JSX syntax, and feels more like other APIs in React. For example, PropTypes (even though it’s being moved into its own package) has a somewhat similar approach.

Cons

Could be a lot of work for a complex component

Polymer’s paper-input element has 37 properties, so it would produce a very large config. If developers are using a lot of custom elements in their app, that may equal a lot of configs they need to write.

May bloat bundle size

Related to the above point, each custom element class now incurs the cost of its definition + its config object size.

Note: I'm not 100% sure if this is true. Someone more familiar with the React build process could verify.

Config needs to keep pace with the component

Every time the component does a minor version revision that adds a new property, the config will need to be updated as well. That’s not difficult, but it does add maintenance. Maybe if configs are generated from source this is less of a burden, but that may mean needing to create a new tool to generate configs for each web component library.

cc @sebmarkbage @gaearon @developit @treshugart @justinfagnani

robdodson commented 6 years ago

Apologies for the long read, but I wanted to make sure I was thoroughly exploring each option. I don't want to bias things too much with my own opinion, but if I were in a position to choose, I think I'd go with option 3.

Option 3 is backwards compatible, declarative, and explicit. There’s no need to maintain a fallback heuristic, and other libraries already provide similar sigils/modifiers.

worawit15379 commented 6 years ago

Apologies for the long read, but I wanted to make sure I was thoroughly exploring each option. I don't want to bias things too much with my own opinion, but if I were in a position to choose, I think I'd go with option 3. Option 3 is backwards compatible, declarative, and explicit. There’s no need to maintain a fallback heuristic, and other libraries already provide similar sigils/modifiers.

jeremenichelli commented 6 years ago

I'm between option 2 and option 3, I think that React has handled behavior and API changes very well in the past. Introducting warnings and links to docs might serve well to help developers understand what's happening under the hood.

Option 3 looks attractive because of its declarative nature, while reading JSX code new coming developers will know immediately what React will do when rendering the element.

cjorasch commented 6 years ago

Comments on option 2

Developers might be confused when React sets an attribute instead of a property depending on how they’ve chosen to load their element.

Do consumers of a custom element need to understand this distinction? Or is that only important to the author of the custom element? It seems like the author of the element will need to handle attributes for anything used in HTML (since that is the only way data gets passed from HTML usage) and properties if they want to support complex values or property get/set from DOM. It is even possible an author could have something initially implemented as an attribute and then later add a property with the same name to support more flexible data types and still back the property with a value stored in the attributes.

Naming collisions with future HTMLElement attributes and properties seems like a weakness in the Web Components standards in general since that can lead to errors regardless of the binding approach.

If an element has an undefined property, and React is trying to pass it an object/array it will set it as a property. This is because some-attr="[object Object]” is not useful.

It seems confusing to bind differently based on the value. If the author of the element has not specified a property getter/setter to handle the value then setting the property would cause the element to behave like the value was never specified which might be harder to debug.

Comments on option 3

Another potential con with option 3 is that it requires the consumer of the custom element to know whether the element has implemented something as a property or as an attribute. If you are using a mix of React components and custom elements it could be confusing to set React props using one syntax and custom element properties using a different syntax.

robdodson commented 6 years ago

Do consumers of a custom element need to understand this distinction? Or is that only important to the author of the custom element?

I doubt it's actually a huge issue because, as you pointed out, the element author should define an attribute and property for the underlying value and accept data from both. I would also add that they should keep the attribute and property in sync (so setting one sets the other).

Naming collisions with future HTMLElement attributes and properties seems like a weakness in the Web Components standards in general since that can lead to errors regardless of the binding approach.

I agree but I'm not sure if this is something React needs to try to work around in their library. It feels like a problem that needs to be solved as part of the custom elements spec. I can see if we can discuss it as part of the upcoming TPAC standards meeting.

I should add, for properties this isn't as bad because the element-defined property will shadow the future property added to HTMLElement. So if you were passing data to a custom element as a js property, it would continue to work. The main issue seems to be around attributes since they are global.

It seems confusing to bind differently based on the value. If the author of the element has not specified a property getter/setter to handle the value then setting the property would cause the element to behave like the value was never specified which might be harder to debug.

In the case where a custom element is lazy loaded and "upgraded", it will initially have undefined properties. This addresses that use case by making sure those elements still receive their data and they can use it post-upgrade.

It's true that if the author doesn't define a getter/setter for a value this would not be very useful. But it's also not useful to have an my-attr=[object Object]. And since you don't know if the property is truly undefined or if they definition is just being lazy loaded, it seems safest to set the property.

Another potential con with option 3 is that it requires the consumer of the custom element to know whether the element has implemented something as a property or as an attribute.

I think you're essentially in the same boat today because there's nothing that forces a custom element author to define an attribute instead of a property. So I could have an element with a properties only API that would not receive any data from React's current system and I would need to know to use ref to directly set the js properties.

Because custom elements are meant as a primitive, there's nothing that enforces creating corresponding attributes and properties. But we're trying very hard to encourage doing so as a best practice, and all of the libraries that I know of today create backing properties for their attributes.

[edit]

As you stated in your earlier point:

It seems like the author of the element will need to handle attributes for anything used in HTML (since that is the only way data gets passed from HTML usage) and properties if they want to support complex values or property get/set from DOM.

Because you never know how a user will try to pass data to your element, you end up needing to have attribute-property correspondence anyway. I imagine if option 3 shipped that most folks would just bind everything using the @ sigil because it'd be easiest. That's how I work with custom elements in Vue today since they expose a .prop modifier.

jeremenichelli commented 6 years ago

it requires the consumer of the custom element to know whether the element has implemented something as a property or as an attribute

That's not something React should worry as Rob said in my opinion, it's the custom element author's responsability to inform the user how the element works.

And it's actually the way that we need to do it today, for example think about the <video> element, let's say you need to mute it or change the current time inside a component.

muted works as a boolean attribute

render() {
  return (
    <div className="video--wrapper">
      <video muted={ this.state.muted } />
    </div>
  );
}

For the current time you need to create a ref pointing to the video element and change the property.

render() {
  return (
    <div className="video--wrapper">
      <video ref={ el => this.video = el } muted={ this.state.muted } />
    </div>
  );
}

Then create an event handler, an instance method and manually set the property to the DOM element.

onCurrenTimeChange(e) {
  this.video.currentTime = e.value;
}

If you think about it it kinda breaks the declarative model React itself imposes with its API and JSX abstract layer since the currentTime it's clearly a state in the wrapper component, with property binding we would still need the event handler but the JSX abstraction model would be more declarative and refs wouldn't be necessary just for this:

render() {
  return (
    <div className="video--wrapper">
      <video muted={ this.state.muted } @currentTime={ this.state.currentTime } />
    </div>
  );
}

My point is that whether you are relying on native or custom elements, you still need to know your way around them based on documentation, the difference that in the second case it should come from the custom element's author.

@cjorasch my two cents :)

effulgentsia commented 6 years ago

If we were designing this from scratch, without needing to consider backwards compatibility, I think option 1 would be the most idiomatic per React’s "JavaScript-centric API to the DOM".

With regard to server-side rendering, could that problem be solved by providing an API for application code to inform React on how to map custom element properties to attributes? Similar to the maps that React already maintains for platform-defined attributes? This API would only need to be invoked once per custom element name (not for each instance of it), and only for properties that don't follow a straight 1:1 correspondence with their attribute, which should hopefully be relatively rare.

If we're concerned about this being too much of a breaking change though, then I think option 3 is pretty appealing as well. If the sigil signifies a property, I would suggest ".", since that's already JavaScript's property accessor. However, I think it's unfortunate to make every instance of where a custom element is used in an application be responsible for knowing when to use an attribute vs. when to use a property. What I prefer about option 1 is that even if a property to attribute map is needed, that mapping code can be isolated from all the JSX usages.

cjorasch commented 6 years ago

In the case where a custom element is lazy loaded and "upgraded", it will initially have undefined properties. This addresses that use case by making sure those elements still receive their data and they can use it post-upgrade.

Maybe I don't understand the upgrade process. Elements would typically have properties defined as getters/setters in the class prototype. Checking propName in element would return true because of the existence of the getter/setter even if the property value was still undefined. During upgrade do property values get set on some temporary instance and then later get copied to the actual instance once the lazy load is complete?

effulgentsia commented 6 years ago

Upgrading is the process by which the custom element receives its class. Prior to that, it's not an instance of that class, so the property getters/setters aren't available.

robdodson commented 6 years ago

@jeremenichelli

muted works as a boolean attribute

just checked and it also has a corresponding property though it doesn't seem to be documented on MDN :P

For the current time you need to create a ref pointing to the video element and change the property.

Yeah occasionally you'll encounter properties-only APIs on modern HTML elements. currentTime updates at a high frequency so it wouldn't make sense to reflect it to an HTML attribute.

My point is that wether you are relying on native or custom elements, you still need to know your way around them based on documentation

Yep there's unfortunately no one-size-fits-all attributes/properties rule. But I think generally speaking you can lean heavily on properties and provide syntax so developers can use attributes in special cases.

jeremenichelli commented 6 years ago

@robdodson yeap, I knew about the muted property too 😄 I just used these two to prove that already in the wild there isn't a one-size-fits-all rule as you mentioned.

We will have to rely on documentation on both native and custom elements, so it's something I wouldn't mind for this decision.

While writing the last code snippet I kinda liked the property binding though 💟

robdodson commented 6 years ago

@effulgentsia

However, I think it's unfortunate to make every instance of where a custom element is used in an application be responsible for knowing when to use an attribute vs. when to use a property.

I think this is already the case today though. Since the major custom element libraries (polymer, skate, possibly others?) automatically create backing properties for all exposed attributes, developers could just use the sigil for every property on a custom element. It would probably be a rare occurrence for them to need to switch to using an attribute.

@cjorasch

RE: upgrade. As @effulgentsia mentioned, it's possible to have a custom element on the page but load its definition at a later time. <x-foo> will initially be an instance of HTMLElement and when I load its definition later it "upgrades" and becomes an instance of the XFoo class. At this point all of its lifecycle callbacks get executed. We use this technique in the Polymer Starter Kit project. Kind of like this:

<app-router>
  <my-view1></my-view1>
  <my-view2></my-view2>
</app-router>

In the above example, we won't load the definition for my-view2 until the router changes to it.

It's entirely possible to set a property on the element before it has upgraded, and once the definition is loaded the element can grab that data during one of its lifecycle callbacks.

effulgentsia commented 6 years ago

developers could just use the sigil for every property on a custom element

If developers started doing that, then how would that differentiate using a property because you "can" from using a property because you "must"? And isn't that a differentiation that's needed for server-side rendering?

robdodson commented 6 years ago

If developers started doing that, then how would that differentiate using a property because you "can" from using a property because you "must"?

Sorry, maybe I phrased that wrong. I meant that developers would likely use the sigil because it would give the most consistent result. You can use it to pass primitive data or rich data like objects and arrays and it'll always work. I think working with properties at runtime is generally preferred to working with attributes since attributes tend to be used more for initial configuration.

And isn't that a differentiation that's needed for server-side rendering?

It might be the case that on the server the sigil would fallback to setting an attribute.

effulgentsia commented 6 years ago

It might be the case that on the server the sigil would fallback to setting an attribute.

I don't think that would work if the reason for the sigil is that it's a property that doesn't exist as an attribute, such as video's currentTime.

differentiate using a property because you "can" from using a property because you "must"

I think this differentiation is important, because there's entirely different reasons for choosing to use an attribute or property as an optimization (e.g., SSR preferring attributes vs. client-side rendering preferring properties) vs. something that exists either as only an attribute or only a property.

With regard to server-side rendering, could that problem be solved by providing an API for application code to inform React on how to map custom element properties to attributes?

To be more specific, I'm suggesting something like this:

ReactDOM.defineCustomElementProp(elementName, propName, domPropertyName, htmlAttributeName, attributeSerializer)

Examples:

// 'muted' can be set as either a property or an attribute.
ReactDOM.defineCustomElementProp('x-foo', 'muted', 'muted', 'muted')

// 'currentTime' can only be set as a property.
ReactDOM.defineCustomElementProp('x-foo', 'currentTime', 'currentTime', null)

// 'my-attribute' can only be set as an attribute.
ReactDOM.defineCustomElementProp('x-foo', 'my-attribute', null, 'my-attribute')

// 'richData' can be set as either a property or an attribute.
// When setting as an attribute, set it as a JSON string rather than "[object Object]".
ReactDOM.defineCustomElementProp('x-foo', 'richData', 'richData', 'richdata', JSON.stringify)

For something that can only be a property (where htmlAttributeName is null), SSR would skip over rendering it and then hydrate it on the client.

For something that can only be an attribute (where domPropertyName is null), React would invoke setAttribute() as currently in v16.

For something that can be both, React could choose whatever strategy is most optimal. Perhaps that means always setting as a property on client-side, but as an attribute server-side. Perhaps it means setting as an attribute when initially creating the element, but setting as a property when later patching from the vdom. Perhaps it means only setting as an attribute when the value is a primitive type. Ideally, React should be able to change the strategy whenever it wants to as an internal implementation detail.

When React encounters a prop for which defineCustomElementProp() hasn't been called and which isn't defined by the HTML spec as a global property or attribute, then React can implement some default logic. For example, perhaps:

But in any case, by keeping this a separate API, the JSX and props objects are kept clean and within a single namespace, just like they are for React components and non-custom HTML elements.

effulgentsia commented 6 years ago

Sorry for the excessive comments, but I thought of another benefit to my proposal above that I'd like to share:

Those ReactDOM.defineCustomElementProp() calls could be provided in a JS file maintained by the custom element author (in the same repository as where the custom element is maintained/distributed). It wouldn't be needed for custom elements with a strict 1:1 correspondence of property/attribute, which per this issue's Background statement is the recommendation and majority case anyway. So only custom element authors not following this recommendation would need to provide the React integration file. If the author doesn't provide it (e.g., because the custom element author doesn't care about React), then the community of people who use that custom element within React apps could self-organize a central repository for housing that integration file.

I think the possibility of such centralization is preferable to a solution that requires every user of the custom element to always have to be explicit with a sigil.

LeeCheneler commented 6 years ago

Option 3 would be my preferred but that's a huge breaking change... What about the inverse? Attributes have a prefix not props?

robdodson commented 6 years ago

@LeeCheneler

Option 3 would be my preferred but that's a huge breaking change... What about the inverse? Attributes have a prefix not props?

Why would it be a breaking change? The current behavior of attributes being the default would remain. The sigil would be opt-in and developers would use it to replace the spots in their code where they currently use a ref to pass data to a custom element as a JS property.

@drcmda

neither new attributes that could break existing projects.

Can you clarify what you meant by this?

robdodson commented 6 years ago

FYI for anyone following the discussion, I've updated the RFC with a 5th option suggested by members of the React team.

gaearon commented 6 years ago

Option 5 seems safest for us. It lets us add the feature without having to make a decision about “implicit” API right now since the ecosystem is still in the “figuring it out” phase. We can always revisit it in a few years.

Polymer’s paper-input element has 37 properties, so it would produce a very large config. If developers are using a lot of custom elements in their app, that may equal a lot of configs they need to write.

My impression is that custom element users in React will eventually want to wrap some custom elements into React components anyway for app-specific behavior/customizations. It is a nicer migration strategy for this case if everything already is a React component, e.g.

import XButton from './XButton';

and that happens to be generated by

export default ReactDOM.createCustomElementType(...)

This lets them replace a React component with a custom component that uses (or even doesn’t use) custom elements at any point in time.

So, if people are going to create React components at interop points, we might as well provide a powerful helper to do so. It is also likely that people will share those configs for custom elements they use.

And eventually, if we see the ecosystem stabilize, we can adopt a config-less approach.

I think the next step here would be to write a detailed proposal for how the config should look like to satisfy all common use cases. It should be compelling enough for custom element + React users, since if it doesn't answer common use cases (like event handling) we're going to end up in the limbo where the feature doesn't provide enough benefit to offset the verbosity.

effulgentsia commented 6 years ago

Building from my earlier comment, how about:

const XFoo = ReactDOM.createCustomElementType('x-foo', {
  propName1: {
    propertyName: string | null,
    attributeName: string | null,
    attributeSerializer: function | null,
    eventName: string | null,
  }
  propName2: {
  }
  ...
});

The logic would then be, for each React prop on an XFoo instance:

  1. If the eventName for that prop is not null, register it as an event handler that invokes the prop value (assumed to be a function).
  2. Else if rendering client-side and propertyName is not null, set the element property to the prop value.
  3. Else if attributeName is not null, set the element attribute to the stringified prop value. If attributeSerializer is not null, use it to stringify the prop value. Otherwise, just do '' + propValue.

Polymer’s paper-input element has 37 properties, so it would produce a very large config.

I'd like to suggest that the config only be necessary for outlier props. For any prop on the XFoo instance that wasn't included in the config, default it to:

effulgentsia commented 6 years ago

Alternatively, maybe it makes sense to keep events in a separate namespace, in which case, remove everything having to do with eventName from the last comment, and instead let events be registered as:

<XFoo prop1={propValue1} prop2={propValue2} events={event1: functionFoo, event2: functionBar}>
</XFoo>
robdodson commented 6 years ago

@gaearon @effulgentsia what do y'all think of a combination of option 1 and option 5?

Option 1 would make it easier for the casual user of a custom element to pass rich data. I'm imagining the scenario where I'm building an app and I just want to use a couple of custom elements. I already know how they work and I'm not so invested that I want to write a config for them.

Option 5 would be for folks who want to use something like paper-input all over their app and would really like to expose its entire API to everyone on their team.

robdodson commented 6 years ago

For SSR of option 1 the heuristic could be always use an attribute if rendering on the server. A camelCase property gets converted to a dash-case attribute. That seems to be a pretty common pattern across web component libraries.

effulgentsia commented 6 years ago

I like the idea of an option1 + option5 combination a lot. Meaning that for most custom elements:

<x-foo prop1={propValue1}>

would work as expected: prop1 set as a property client-side and as a (dash-cased) attribute server-side.

And people could switch to option5 for anything for which the above doesn't suit them.

It would be a breaking change though from the way React 16 works. For anyone who experiences that breakage (e.g., they were using a custom element with attributes that aren't backed by properties), they could switch to option5, but it's still a break. I leave it to the React team to decide if that's acceptable.

LeeCheneler commented 6 years ago

Ah, this is what I get for reading this quickly on the train @robdodson 🤦‍♂️ ... Not really a fan of option 3 now 🤔 I read it as an all in on props being prefixed, hence my hesitation.

Option 5 seems reasonable and straightforward.

I like where @effulgentsia is heading. Is there a reason it couldn't be:

const XFoo = ReactDOM.createCustomElementType('x-foo', {
  propName1: T.Attribute,
  propName2: T.Event,
  propName3: T.Prop
})

Or is supporting multiple types on a single prop valuable?

I'd be hesitant with this flow though @effulgentsia:

if the value is a function: eventName: the prop name, else: propertyName: the prop name, attributeName: camelCaseToDashCase(the prop name),

I don't think I'd want a function prop to default to an event, and is assigning both propertyName and attributeName sensible? When would you want both supported to mimic the question above? 🙂

effulgentsia commented 6 years ago

@LeeCheneler:

Quoting from the issue summary's Option 1 pros:

Any element created with libraries like Polymer or Skate will automatically generate properties to back their exposed attributes. These elements should all "just work" with the above approach. Developers hand-authoring vanilla components are encouraged to back attributes with properties as that mirrors how modern (i.e. not oddballs like <input>) HTML5 elements (<video>, <audio>, etc.) have been implemented.

So that's the reason why assigning both propertyName and attributeName is sensible: because it reflects what is actually the case for elements that follow best practice. And by making React aware of that, it allows React to decide which to use based on situation: such as using properties for client-side rendering and attributes for server-side rendering. For custom elements that don't follow best practice and have some attributes without corresponding properties and/or some properties without corresponding attributes, React would need to be aware of that, so that attribute-less-properties aren't rendered during SSR and property-less-attributes can be set with setAttribute() during client-side rendering.

With your proposal, that could potentially be done by bit-combining flags, such as:

propName1: T.Property | T.Attribute,

However, that wouldn't provide a way to express that the attribute name is different from the property name (e.g., camelCase to dash-case). Nor would it provide a way to express how to serialize a rich object to an attribute during SSR (the current behavior of "[object Object]" isn't useful).

I don't think I'd want a function prop to default to an event

Yeah, I think I agree with that as well, hence the follow-up comment. Thanks for validating my hesitance with that!

effulgentsia commented 6 years ago

Here's a thought for a less verbose version of my earlier suggestion:

const XFoo = ReactDOM.createCustomElementType('x-foo', {
  UNREFLECTED_ATTRIBUTES: [
    'my-attr-1',
    'my-attr-2',
  ],
  UNREFLECTED_PROPERTIES: [
    'myProp1',
    'myProp2',
  ],
  REFLECTED_PROPERTIES: {
    // This is default casing conversion, so could be omitted.
    someVeryLongName1: 'some-very-long-name-1',

    // In case anyone is still using all lowercase without dashes.
    someVeryLongName2: 'someverylongname2',

    // When needing to define a function for serializing a property to an attribute.
    someRichData: ['some-rich-data', JSON.stringify],
  },
});

And per the code comment above, I strongly urge not requiring every reflected property to be defined, but rather default anything that isn't defined as automatically being a reflected property whose attribute name is the dash-cased version.

LeeCheneler commented 6 years ago

Makes sense @effulgentsia 👍

I like your second example but is it not open to combinatorial explosion if more types gets added, ala events + whatever might make sense?

- UNREFLECTED_ATTRIBUTES
- UNREFLECTED_PROPERTIES
- UNREFLECTED_EVENTS
- REFLECTED_PROPERTIES_ATTRIBUTES
- REFLECTED_PROPERTIES_EVENTS
- REFLECTED_ATTRIBUTES_EVENTS
- REFLECTED_PROPERTIES_ATTRIBUTES_EVENTS
...

Although I suppose you wouldn't want to mix an event with a prop or attribute anyway 🤔 Attribute & prop are probably the only things you'd want to mimic.

treshugart commented 6 years ago

I think there is an opportunity here for both the React and Web Component community to align on a best practice. React having an opinion here will go a long way in custom element authors being guided in the right direction due to its widespread adoption and weight that its opinions carry.

Although I've authored the implementation of option 4, I'm always caught up by having to separate attributes and events from properties. Ideally, I'd prefer option 1. Practically, I think I'd prefer option 2 with an escape hatch.

Option 1 is ideal but there are many types of attributes that don't have corresponding properties (aria / data), so it'd require extra heuristics around these and if there's any edge-cases where elements may have an attribute that should have a property, but do not implement one for whatever reason. I feel this is an option that should be considered carefully, but may be viable long-term.

Option 2 is preferable because it's a non-breaking change. It will work for all situations where the custom element definition is registered prior to an instance being created (or loaded before properties are set). Prior art for this option is Preact (cc @developit) and it's worked well thus far. Going down this path gives a reasonably robust, non-breaking implementation that has been proven by a successful React variant and it works in most situations. If anything, it gives React a short-term solution while better solutions are assessed for the long-term.

For the situation (situations?) where it doesn't work - deferred loading of custom element definitions and any others that we haven't covered - an escape hatch like what Incremental DOM has done, could be implemented. This is similar to what @effulgentsia is proposing, but would scale better to x number of custom elements. If consumers want to do it on a per-custom-element basis, they still can, because it's just a function. This allows React to have an opinion, escape hatch and satisfy all use-cases by handing off the responsibility to the consumer for all edge-cases. This is also something that I've previously discussed with @developit about implementing in Preact. Alignment between Preact / React here would be a big win.

About the concern with future HTML attributes, this is something that we can't solve, so I don't think we should get caught up in concerning ourselves with it here.

TimvdLippe commented 6 years ago

Those ReactDOM.defineCustomElementProp() calls could be provided in a JS file maintained by the custom element author

This would tie the custom element implementation to library-specific implementation (in this case React). In my opinion that is too high of a burden on custom elements authors. Moreover, for authors that do not use React, convincing them to ship the definition gets into politics discussions that no one wants.

Defining the invocation of such an API by the user of a custom element with only the properties/attributes the user actually uses is less code to maintain and more expressive.

sophiebits commented 6 years ago

Even if a library author does not use React, I am arguing it is a better UX for the client of those web components to define the property configuration once and then use it.

The first time you use a web component that needs a property, it is just as hard as adding a sigil (more verbose, but also more explicit) but then it is easier for subsequent uses because you don't need to think about it for every single callsite of that component. In either case you need to understand properties/attributes difference when adopting a new web component, but with the single shared configuration you don't need every user of that component within the same app to think about it.

We could potentially allow remapping property names in that configuration to allow making more React-idiomatic names there. The upgrade path to a more sophisticated wrapper, if one were ever needed, is also smoother since you can just replace XFoo with a custom React component that does whatever fancy translation logic it needs.

Basically: if it's possible for people to not think about the property configuration every time they use a component, I'd rather that approach. That's why I suggested option 5. I think it is more ergonomic than 3 and 4 while being equally flexible.

Option 1 and 2 don't work super well with server rendering (HTML generation), and option 2 also creates upgrade hazards for web component authors where now adding a property with the same name as an existing attribute is a breaking change. If we decide that SSR isn't useful then option 1 is pretty appealing from a React perspective. I'm not familiar if it would be comprehensive enough in practice though – do component authors expose everything via properties?

robdodson commented 6 years ago

@treshugart without getting too deep into bikeshedding, do you think you could show how you'd expect the "escape hatch" to work? Pseudo code is fine. Just so we're all on the same page.

robdodson commented 6 years ago

Sorry @sophiebits just now seeing your reply. I'd like to respond to a few of the points after reading through it a few more times but wanted to quickly respond to this one:

I'm not familiar if it would be comprehensive enough in practice though – do component authors expose everything via properties?

Any component built with Polymer or Skate will expose everything via properties. There might be a few rare outliers (maybe setting an attribute just for styling or something) but otherwise I think things are always backed by properties. I'm pretty confident that the majority of in-production web components are built using one of these two libraries.

If someone is hand-authoring a vanilla web component there is nothing that forces them to expose everything via properties but we encourage they do so in our best practices docs and examples.

For what it's worth, there's also nothing forcing them to use attributes. A custom element definition is just a class so the developer can do whatever they want. But in practice most folks prefer using an abstraction like Polymer or Skate to mint their components, so they're getting a properties API for free.

sophiebits commented 6 years ago

Maybe then the best approach is to do properties always on the client side and then support an Option 5–style configuration map of primitive property names to attribute names for people who want to support SSR in their apps.

effulgentsia commented 6 years ago

@sophiebits: I think that's a great idea, except to the extent that it's a breaking change for people who've written their React apps using attribute names. For example:

<x-foo long-name={val} />

But what about a rule for "do properties" if the propname doesn't have dashes and "do attributes" if it does?

@robdodson: are you aware of any custom element frameworks or practices out there where people would have different casing of attributes from the corresponding property, without containing a dash? I.e., a longname attribute with a longName property? That actually seems to be the much more common pattern with built-in HTML elements and global attributes (e.g., contenteditable => contentEditable), but I'm unclear as to if it's now sufficiently discouraged for custom element attributes thanks to Polymer and Skate. If it's still an issue, then existing JSX with:

<x-foo longname={val} />

would fail as a property set if the property is longName.

treshugart commented 6 years ago

@effulgentsia I can only speak for Skate, but we only recommend using the attribute API if writing HTML, which - for all intents and purposes - can also be classified as server rendering. If you're doing anything via JS, you should be setting props. Our props API automatically does a one-way sync / deserialisation from attributes, and derives the attribute name by dash-casing the property name (camelCase becomes camel-case, etc). This behaviour as a whole is configurable but we encourage the best practice to be the aforementioned.

As stated by many, props make SSR hard, and this is a valid concern. Since it sounds like most would prefer option 1, maybe we try and push forward with @sophiebits's proposal of setting props on the client while providing a fallback / mapping? I assume this means that attributes will be set on the server?

For the sake of an example, here's how you could implement carrying over state and props from the server to the client with Skate (and any custom element that implements a renderedCallback() and props and / or state setters. Doing so at the custom element level is trivial. If React went down the road of setting attributes on the server, rehydration would essentially be the same. Skate component authors actually wouldn't have to do anything as we'd already provide the deserialisation logic for them.

@robdodson I would do a similar thing to what Incremental DOM is doing. This would look something like:

const isBrowser = true; // this would actually do the detection
const oldAttributeHook = ReactDOM.setAttribute;

// This is much like the IDOM impl but with an arguably more clear name.
ReactDOM.setAttribute = (element, name, value) => {
  // This is essentially option 2, but with the added browser check
  // to keep attr sets on the server.
  if (isBrowser && name in element) {
    element[name] = value;
  } else {
    oldAttributeHook(element, name, value);
  }
};
robdodson commented 6 years ago

@sophiebits

option 2 also creates upgrade hazards for web component authors where now adding a property with the same name as an existing attribute is a breaking change.

I think this may be unavoidable given the way attributes work in the platform. If you SSR a custom element, and therefore must write to an attribute, you also run the risk that the platform will ship a similarly named attribute in the future. As @treshugart mentioned before, I don't think it's something React (or really any library) is empowered to solve. This is something I want to take up with the web component spec authors at TPAC to see if we can fix it in the custom element space.

I'm not sure if that changes your mind at all about option 2 😁 but I wanted to mention it since option 2 has a few nice bonuses and Preact seems to be proving it out in practice.

Maybe then the best approach is to do properties always on the client side and then support an Option 5–style configuration map of primitive property names to attribute names for people who want to support SSR in their apps.

+1, I'm supportive of continuing to head in this direction.


@effulgentsia

I think that's a great idea, except to the extent that it's a breaking change for people who've written their React apps using attribute names.

Option 2 would solve that :) Otherwise there would probably need to be a heuristic coupled with option 1 that maps dash-cased attributes to camelCased properties.

But what about a rule for "do properties" if the propname doesn't have dashes and "do attributes" if it does?

It looks like Preact will set the attribute if there's a dash in the name. I'm assuming that's because they use option 2 and long-name doesn't pass the in check so it falls back to an attribute (source).

I personally like this behavior, but it gets back into the realm of setting attribute and possible future conflicts so I think @sophiebits should weigh in.

are you aware of any custom element frameworks or practices out there where people would have different casing of attributes from the corresponding property, without containing a dash?

Not that I know of. The dash is an easy way for the library to know where to camel case. If you were hand-authoring a vanilla web component you could do longname/longName and only option 2 would save you because it wouldn't find a longname property, but it'd fallback to the previously used longname attribute.

For what it's worth, it looks like Preact, as a last resort, will call toLowerCase() on a property it doesn't recognize before setting the attribute. So if you were SSR'ing <x-foo longName={bar}/> it would also properly fall back to the longname="" attribute.


@treshugart

maybe we try and push forward with @sophiebits's proposal of setting props on the client while providing a fallback / mapping? I assume this means that attributes will be set on the server?

yes, and yes.

I would do a similar thing to what Incremental DOM is doing

Is the idea that every element (or their base class) would need to do mix this in?

robdodson commented 6 years ago

btw, thank you all for continuing to participate in the discussion, I know it's gotten quite long ❤️

gaearon commented 6 years ago

Not sure I understand the last example in https://github.com/facebook/react/issues/11347#issuecomment-339858314 but it’s highly unlikely we’d provide a global overridable hook like this.

developit commented 6 years ago

@gaearon I think Trey was just showing the net change as a monkey-patch, presumably it'd be written into the ReactDOM implementation itself.

effulgentsia commented 6 years ago

Based on the recent comments, what do you all think of this proposal?

  1. For BC, don't change anything about how lowercase custom elements work in React. In other words, JSX like <x-foo ... /> would continue to work the same way in React 17 as in 16. Or, if minor bug fixes are wanted for it, open a separate issue to discuss those.

  2. Add a config-less API to create a React component with better custom element semantics. E.g., const XFoo = ReactDOM.customElement('x-foo');.

  3. For the component created above, employ the following semantics:

    • For any prop on XFoo that is a reserved React prop name (children, ref, any others?), apply the usual React semantics to it (do not set it as either an attribute or property on the custom element DOM node).
    • For any HTMLElement global attribute or property defined by the HTML spec (including data-* and aria-*), do the same thing with those props as what React would do with them if they were on a div element. In other words, how React applies the props on <XFoo data-x={} className={} contentEditable={} /> to the DOM node should be identical to how it does so for <div data-x={} className={} contentEditable={} /> (both for client-side and for SSR).
    • For any prop on XFoo that contains a dash (other than the global attributes permitted above), emit a warning (to inform the developer that XFoo is a property-centric, not an attribute-centric, API) and do nothing with it (neither set it as a property nor an attribute).
    • For any prop on XFoo that starts with an underscore or an upper ASCII letter, do nothing with it (and maybe emit a warning?). Neither is a recommended way to name properties for custom elements, so reserve those namespaces for future semantics (for example, see #4 below).
    • For all other props on XFoo, when rendering client-side, set it on the DOM node as a property. For SSR, if the value is primitive, render it as an attribute; if non-primitive, skip rendering and set it as a property client-side during hydration. For SSR rendering as an attribute, camelCaseToDashCase the name.
  4. For components created via the API in #2 above, reserve a prop name to use for event listeners. E.g., 'events' or 'eventListeners'. Or, if not wanting to conflict with those potential custom element property names, then '_eventListeners' or 'EventListeners'. The ReactDom-created implementation of XFoo would automatically register these event listeners on the DOM node.

  5. For edge cases (e.g., using a custom element for which the above implementation isn't desired or sufficient), the app developer could implement their own React component to do whatever special thing they need. I.e., they don't need to use ReactDOM.customElement() or they could extend it.

  6. For people who want all of the above behavior, but want their JSX to use the lowercase custom element names (<x-foo /> instead of <XFoo />, for similar reasons that people familiar with writing HTML prefer <div> over <Div>), they can monkey-patch React.createElement(). It would be a pretty simple monkey patch: just take the first argument and if it matches a custom element name you want this for (whether that's a specific list or any string with all lowercase letters and at least one dash), then invoke ReactDOM.customElement() on that name and forward the result and remaining arguments to the original React.createElement().

treshugart commented 6 years ago

@developit @gaearon it could be either. If a "mapping" was necessary, I think a hook is more sustainable. However, that was also intended to show the net change if it were to be implemented in ReactDOM's core, as Jason pointed out.

robdodson commented 6 years ago

For BC, don't change anything about how lowercase custom elements work in React. In other words, JSX like <x-foo ... /> would continue to work the same way in React 17 as in 16. Or, if minor bug fixes are wanted for it, open a separate issue to discuss those.

Personally I'd prefer to be able to use my <x-foo> element, as is, and easily pass it properties without first needing to wrap it.

If possible I'd rather go with @sohpiebits' suggestion of option 1 (client-side properties) and 5 (config for SSR). I'm still holding out hope that maybe folks will reconsider option2 (maybe option 2 + 5?) for the backwards compatability bonus.

@gaearon does your opinion change on Trey's proposal if it's part of ReactDOM core? Maybe we could flesh out the example more if that would help?

jeremenichelli commented 6 years ago

My main concern with Option 5 is creating a lot of boilerplate to allow interoperability, breaking the DX, it would be a shame for all the React core team and contributors to spend a lot of time in changes that won't have the desired impact.

I really loved how the React team handled the last changes in the repo, like PropTypes, it would be good to think of a plan involving more than just one switch, to educate developers in possible changes to do in the future for custom and not custom elements.

I think that the solution that will satisfy all of us will be one combining some of this options as steps, API addition, warning and deprecation or behavior change.

Maybe options 5, with warning, later option 2 with deprecation of the needed wrapper.

robdodson commented 6 years ago

Maybe options 5, with warning, later option 2 with deprecation of the needed wrapper.

I was actually thinking that doing the opposite would be a better series of steps. Option 1 or 2 because it's less of a dramatic change. And measuring how that goes and what the SSR story starts to look like for web components. Then following up with option 5 because it adds a new API and a notion of proxy/wrapper components.

effulgentsia commented 6 years ago

The main problem with option 1 is that it's a pretty large BC break. The main problem with option 2 is that it has a race condition depending on when the element is done upgrading. I'm not sure that either of those is truly acceptable for a project that's as widely used as React is.

Given the availability of option 5, I wonder if we can instead make much safer, but still useful, improvements to non-option-5 usages. For example, how about the inverse of option 4: simply introduce domProperties and eventListeners props, so you can do stuff like:

<x-foo 
  my-attr1={...} 
  domProperties={{myRichDataProperty: ...}} 
  eventListeners={{'a-custom-element-event':  e => console.log('yo')}} 
/>

This is fully backwards compatible, because by virtue of their uppercase letters, domProperties and eventListeners are not valid attribute names. Except for that React 16 currently calls setAttribute() even for prop names with upper alphas, relying on the browsers to internally lowercase the name; however, could a future minor release of React 16 emit a warning when encountering custom element props that are not valid attribute names, so that people can fix their casing mistakes prior to upgrading to React 17?

In addition to preserving BC, this approach is easy to understand: it's attribute-centric (meaning React props are treated as element attributes), which fits given that the element name itself is all lowercase and has a dash and is therefore HTML-centric. However, domProperties is provided for the relatively rare cases where you need to pass properties, such as to pass rich data.

For people who want to switch their mental model to be property-centric (ala Option 1), that's where an option 5 style API could come in:

const XFoo = ReactDOM.customElement('x-foo');
<XFoo prop1={} prop2={} data-foo={} aria-label={} />

With this syntax, every prop is treated as a property (option 1). Which fits, because the element "name" (XFoo) is also following a JS-centric convention. I think we'd still want to at a minimum support data-* and aria-* props treated as attributes, which we could either limit to just those, or generalize to treating any prop with a dash as an attribute.

Meanwhile, to support option 5 configuration of SSR, we could add a config API to ReactDOM.customElement, such as:

const XFoo = ReactDOM.customElement('x-foo', ssrConfiguration);

Perhaps ssrConfiguration could be a callback function similar to the ReactDOM.setAttribute one in @treshugart's comment?

What do you think?

treshugart commented 6 years ago

@effulgentsia I like where your thoughts are going. Bikeshedding the names a bit: domProps / domEvents. This is very close to option 4.

WRT SSR, I think SSR can be handled by the custom elements themselves so long as React could respect attributes the component mutates onto itself if it's not tracking them. I posted a gist earlier, but here it is again, for convenience: https://gist.github.com/treshugart/6eff0da3c0bea886bb56589f743b78a6. Essentially the component applies attributes after rendering on the server and rehydrates them on the client. SSR for web components is possible, but solutions are still being discussed at the standards level, so it may be best to wait on this part of the proposal.

robdodson commented 6 years ago

@effulgentsia I also like where you're heading. @sophiebits, @gaearon do y'all have thoughts on this direction?

On Tue, Oct 31, 2017, 7:33 PM Trey Shugart notifications@github.com wrote:

@effulgentsia https://github.com/effulgentsia I like where your thoughts are going. Bikeshedding the names a bit, it might be useful to align their naming: domProps / domEvents, or something.

WRT option 2, it's at least backward compatible and solves most use-cases, but I'm coming around to the alternatives.

I think SSR can be handled by the custom elements themselves so long as React could respect attributes the component mutates onto itself if it's not tracking them. I posted a gist earlier, but here it is again, for convenience: https://gist.github.com/treshugart/6eff0da3c0bea886bb56589f743b78a6. Essentially the component applies attributes after rendering on the server and rehydrates them on the client. SSR for web components is possible, but solutions are still being discussed at the standards level, so it may be best to wait on this part of the proposal here.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/facebook/react/issues/11347#issuecomment-340960798, or mute the thread https://github.com/notifications/unsubscribe-auth/ABBFDeiQhBWNGXNplbVV1zluYxT-ntFvks5sx9hngaJpZM4QD3Zn .

effulgentsia commented 6 years ago

Bikeshedding the names a bit: domProps / domEvents.

I like those. I'm also brainstorming on if there's a way to make them even more idiomatic to React by replacing the concept of "dom" with the concept of "ref". So in other words: refProps / refEvents, since they're about attaching props and event listeners to the "ref".

And then I thought, what if instead of introducing new special names inside of this.props, we simply overload the existing ref JSX attribute. Currently, "ref" is a function that is called when the React component is mounted and unmounted. What if we allowed it to also be an object as so:

<x-foo my-attr-1={}
  ref={{
    props: ...
    events: ...
    mounted: ...
    unmounted: ...
  }}
/>

Just an idea.