Skip to content

Latest commit

 

History

History
1153 lines (886 loc) · 82 KB

0000-reduce-fragmentation.md

File metadata and controls

1153 lines (886 loc) · 82 KB
title author date updated
React DOM for Native
Nicolas Gallagher
2022-08-03
2023-01-31

RFC: React DOM for Native

Summary

This is a proposal to incrementally reduce the API fragmentation faced by developers using React to target multiple platforms via code shared between native and web. The proposed cross-platform user interface APIs are a subset of existing web standards for DOM, CSS, and HTML - "Strict DOM". The proposed changes are overwhelmingly additive and do not require migration of existing React Native UI code (deprecations are optional / follow up work). Incremental progress can help to reduce the fragmentation between React Native and React DOM components, while the ability to run React DOM code (with minor modifications) on native is a longer-term goal.

Motivation

React Native currently includes many APIs that are modelled on Web APIs but do not conform to the standards of those Web APIs. React Native also includes many APIs that achieve the same results on Android and iOS but are exposed as 2 different props. And React Native includes several APIs that have known performance (network and runtime) drawbacks on Web.

This proposal aims to allow developers to target more platforms with cross-platform APIs, and deliver better performance when targeting browsers. Features for Android, iOS, and Web are unified by aligning with the Web standard. Supporting standards helps to:

  • minimize the overhead when running in browsers;
  • reduce developer education required to learn features;
  • set clear and cohesive API end-state expectations for contributors to aim for;
  • accelerate the framework's development by avoiding API design costs;
  • support backwards compatibility;
  • develop universal codebases.

The existing solution for targeting web with React Native is to use React Native for Web. React Native for Web is a user-space library built on top of React DOM and native DOM APIs. It shims React Native components and APIs on the web. The tooling for an existing React DOM app simply maps the 'react-native' export to 'react-native-web'.

This is the most complete and widely used shim, but comes with considerable DX and UX costs on the web. The shim must implement a large surface area of fragmented APIs, and it needs to modify standard APIs and objects (e.g., events) to match React Native's non-standard implementations.

In contrast, implementing a "Strict DOM" subset in React Native shifts the weight of bridging native and web apps onto React Native, where it can be done most efficiently. Although React Native will not support all the features available on web, it will still support a greater expanded feature set relative to React Native today. On the web, we would only need to combine React DOM with a white-label CSS compiler like stylex.

Detailed design

The "complete" API involved is broken down into the following sections.

  • Environment API. Global APIs to add to the host environment.
  • Elements API. DOM APIs to add to host component instances.
  • Components API. React DOM components to add to React Native.
  • Props API. React DOM component props to add to new components, and existing React Native components as part of an incremental strategy.
  • Styling API. CSS APIs to add to the React Native environment.

A simplified example of the user-space code we'd aim to support is as follows:

import { html, css } from 'react-native/dom';

export function VStackPanel(props) {
  const connectedCallback = function (node) {
    const handler = () => {
      const { offsetWidth } = e.target;
      // ...
    };
    const options = { capture: true };
    node.addEventListener('pointerdown', handler, options);
    return function disconnected() {
      node.removeEventListener('pointerdown', handler, options)
    }
  };

  return (
    // Use HTML element
    <html.div
      children={props.children}
      // Synchronous click event that matches W3C event type
      on-click={props.click}
      // Use HTMLElement instance API
      ref={connectedCallback}
      // Use optimized styles
      style={css(
        { flexDirection: 'column', flex: 1 },
        props.style
      )}
    />
  )
}

But there are many incremental steps that can be taken along the way.

Implementation and adoption strategy

The proposal is to support both an incremental adoption strategy, as well as a separate "React DOM" bindings exports. The incremental strategy would find ways to align existing APIs in React Native with their React DOM equivalents, and gradually deprecate the non-standard APIs. Whereas the separate bindings export would be designed to provide most of what is needed for a direct compatibility layer with React DOM.

This would ensure a significant amount of overlap between the existing React Native components and the dedicated "React DOM" compatibility API, allowing for co-mingling of code and reduced developer education. There is no suggestion of deprecating the current React Native components and APIs at this stage.

Reduce API fragmentation across platforms

The initial step is to incrementally reduce existing API fragmenetation across platforms. This involves consolidating the different props, styles, and events for similar functionality across different platforms. The APIs that we consolidate upon are the W3C standards, as React Native is already fairly closely aligned with these standards.

Doing this will make it easier for web developers to work with React Native's existing components and related APIs. This is the path for developers to gradually migrate their existing React Native code into a form that is more aligned with the web. And it will allow React Native for Web to be smaller and faster, providing better results on web via the existing tools that developers use today.

One example of this kind of incremental change is to map props in the existing core components (i.e., View, Text, etc.) to the W3C equivalents: id to nativeID, aria-label to accessibilityLabel, and so on. React Native for Web currently "owns" this translation step, but we would instead move it into React Native to claw back performance on web. For developers familiar with React DOM, there will be less of a learning curve to applying that knowledge to React Native.

<View
  aria-hidden={false}
  aria-label="Accessibility label"
  id="native-id"
  on-click={handleDOMClick}
  on-pointerdown={handlePointerDown}
  role="button"
  tabIndex={0}
>
<Image
  alt="Alternative text"
  crossOrigin="anonymous"
  srcSet="https://image.png 1x, https://image2.png 2x"
  width={320}
>
<TextArea
  autoComplete="email"
  inputMode="email"
/>

<TextArea
  multiline
  readOnly
  rows={3}
/>

Example of how to map srcSet to source:

const { crossOrigin, referrerPolicy, srcSet } = props;
const source = [];
const srcList = srcSet.split(', ');
srcList.forEach((src) => {
  const [uri, xscale] = src.split(' ');
  const scale = parseInt(xscale.split('x')[0], 10);
  const headers = {};
  if (crossOrigin === 'use-credentials') {
    headers['Access-Control-Allow-Credentials'] = true;
  }
  if (referrerPolicy != null) {
    headers['Referrer-Policy'] = referrerPolicy;
  }
  source.push({ headers, height, scale, uri, width });
});

Example of how to map autoComplete to Android's autoComplete and iOS's textContentType:

// https://reactnative.dev/docs/textinput#autocomplete-android
const autoCompleteAndroid = {
  'address-line1': 'postal-address-region',
  'address-line2': 'postal-address-locality',
  bday: 'birthdate-full',
  'bday-day': 'birthdate-day',
  'bday-month': 'birthdate-month',
  'bday-year': 'birthdate-year',
  'cc-csc': 'cc-csc',
  'cc-exp': 'cc-exp',
  'cc-exp-month': 'cc-exp-month',
  'cc-exp-year': 'cc-exp-year',
  'cc-number': 'cc-number',
  country: 'postal-address-country',
  'current-password': 'password',
  email: 'email',
  name: 'name',
  'additional-name': 'name-middle',
  'family-name': 'name-family',
  'given-name': 'name-given',
  'honorific-prefix': 'namePrefix',
  'honorific-suffix': 'nameSuffix',
  'new-password': 'password-new',
  off: 'off',
  'one-time-code': 'sms-otp',
  'postal-code': 'postal-code',
  sex: 'gender',
  'street-address': 'street-address',
  tel: 'tel',
  'tel-country-code': 'tel-country-code',
  'tel-national': 'tel-national',
  username: 'username'
};

// https://reactnative.dev/docs/textinput#textcontenttype-ios
const autoCompleteIOS = {
  'address-line1': 'streetAddressLine1',
  'address-line2': 'streetAddressLine2',
  'cc-number': 'creditCardNumber',
  'current-password': 'password',
  country: 'countryName',
  email: 'emailAddress',
  name: 'name',
  'additional-name': 'middleName',
  'family-name': 'familyName',
  'given-name': 'givenName',
  nickname: 'nickname',
  'honorific-prefix': 'name-prefix',
  'honorific-suffix': 'name-suffix',
  'new-password': 'newPassword',
  off: 'none',
  'one-time-code': 'oneTimeCode',
  organization: 'organizationName',
  'organization-title': 'jobTitle',
  'postal-code': 'postalCode',
  'street-address': 'fullStreetAddress',
  tel: 'telephoneNumber',
  url: 'URL',
  username: 'username'
};

Where possible we should make these changes to the native code. However, we will prioritize user-space shims in JavaScript where they are faster to ship and allow us to gather feedback/support for this overall direction.

Beyond props, there is also the opportunity to reduce fragementation in styling APIs.

  • Don't hard crash on unknown or invalid style properties and values.
  • Deprecate StyleSheet.absoluteFill. Use position:'absolute';inset:0; instead.
  • Deprecate StyleSheet.absoluteFillObject.
  • Deprecate StyleSheet.compose(). Use existing [ a, b ] syntax instead.
  • Deprecate StyleSheet.flatten(). This API encourages runtime introspection of styles in render calls. This pattern is a performance cost (flattening arrays of objects), and prevents us from supporting build-time optimizations for web (e.g., extracting styles to CSS files).
  • Deprecate or rename setStyleAttributePreprocessor (e.g., unstable_setStyleAttributePreprocessor).
  • StyleSheet.create() should obfuscate styles to prevent introspection (i.e., revert identify function change). On web, we need to be able to remove the JavaScript style objects from bundles to support build-time optimization like extraction to CSS files.

To encourage React Native library and product developers to proactively migrate to these new APIs, React Native for Web plans to only support these W3C standards-based APIs in future versions. This will allow us to incrementally add APIs to React Native without needing to commit to simultaneously deprecating APIs and migrating existing React Native code. Existing React Native developers must adopt these APIs if they wish to support web.

Create a separate package or export for DOM bindings

The next step would be to begin exporting separate React DOM bindings from React Native. This would aim to allow code originally written with React DOM to run on React Native with only minor modifications. There would be no need to use React Native for Web, and the web layer in this scenario would be a lot smaller, limited mostly to implementing the modern W3C events API and integrating a style API that allows for static extraction to optimized CSS.

Even this can be done in incremental fashion, with early (user-space) prototypes to get feedback. Most tags can be mapped to existing React Native components and props, in the reverse of the mapping used by React Native for Web.

Equivalent API for Web

In parallel, a user-space layer over React DOM would ensure equivalent APIs between native and web, by converging them both towards a desired the "end state" where the differences between React Native and React DOM are erased while landing on a "modern" flavor of React DOM.

The benefit of initially doing this in user-space is that it reduces the burden of complex migratations for React Native and React DOM (e.g., the changes to React DOM event types, the style prop, and explicit imports of component types), while allowing us to validate and iterate on the proposed end-state APIs with interested parties. This is currently blocked on OSS-ing of stylex.

How we teach this

Teaching these APIs is simplified by developer familiarity with existing DOM / React DOM APIs.

Drawbacks

Many of these features can be shimmed in user-space, at the cost of runtime overhead for native or web platforms. The runtime overhead for web is untenable. The runtime overhead of shifting shims into the React Native JS has yet to be established.

This adds redundancy to the React Native API, as the proposal is to make additive changes and avoid requiring removal of existing APIs in the short term.

We have to be very intentional about how much compatibility with open web standards we can promise. Some cross-platform limitations are rooted in significant differences in the host platforms APIs (e.g., accessibility) and the lack of 99% compat may frustrate users.

Aiming for a degree of React DOM compatibility shifts the burden of missing features onto React Native. Developers may not be used to an API that is complete on web but partially implemented on native platforms.


Environment APIs

window

Events

  • Receives all W3C events dispatched to components (capture and bubble phase). Resolves proposal #249.
  • Dispatches resize.

Properties

Methods

APIs

  • window.fetch
  • window.matchMedia. Resolves proposal #350.
  • IntersectionObserver API for observing the intersection of target elements. This can also be used as a building block for performance tooling.
  • MutationObserver API for watching changes to the host node tree. This can also be used as a building block for performance tooling.
  • ResizeObserver API for responding the changes in the size of elements. Note that this API no longer includes positional coordinates and is optimized for width/height information.

document

Support the document object for common patterns such as listening to visibility changes, and listening to capture or bubble phase events for the entire application (e.g., "outside click" pattern), etc.

The document object might not be exposed as a global, and would instead be accessed via node.getRootNode() to ensure code accounts for multi-window / multi-root scenarios that are more common for React Native apps than React DOM apps (rendering into sourceless iframes is a similar use case).

Events

Properties

Methods


Elements API (DOM subset)

Subset of cross-platform DOM APIs exposed on element instances. This would be an imperative API for working with the Shadow tree in React Native. Based on data from MDN Web API, please refer to the MDN links for complete DOM APIs and comment if you believe any should be included in the proposed subset.

In practice, this DOM API subset is generally limited to the “best practice” APIs that can safely be used with React DOM (i.e., read-only operations that don’t modify the DOM tree), and most React components should already be limited to this subset. One of the important details of this API are how it supports the different ways of determining the dimensions of elements.

EventTarget

The EventTarget API is implemented in JS environments, and should be available on React Native host elements. This feature is commonly used on web, and could be used by React Native developers to support more complex features without first requiring further core API changes to support each use case.

Methods

Event and CustomEvent

Event() and CustomEvent() represent events initialized by developers and that can be dispatched to elements using EventTarget.dispatchEvent().

Node

The DOM Node interface is an abstract base class upon which many other DOM API objects are based, thus letting those object types to be used similarly and often interchangeably. All objects that implement Node functionality are based on one of its subclasses. Every kind of host node is represented by an interface based on Node.

In some cases, a particular feature of the base Node interface may not apply to one of its child interfaces; in that case, the inheriting node may return null or throw an exception, depending on circumstances.

Static properties

Node type constants

  • Node.ELEMENT_NODE (1)
  • Node.TEXT_NODE (3)
  • Node.DOCUMENT_NODE (9)

Document position constants

  • Node.DOCUMENT_POSITION_DISCONNECTED (1)
  • Node.DOCUMENT_POSITION_PRECEDING (2)
  • Node.DOCUMENT_POSITION_FOLLOWING (4)
  • Node.DOCUMENT_POSITION_CONTAINS (8)
  • Node.DOCUMENT_POSITION_CONTAINED_BY (16)

Instance properties

Instances methods

Node inherits methods from its parent, EventTarget.

Element

Element is the most general base class from which all element objects (i.e. objects that represent elements) in a Document inherit. It only has methods and properties common to all kinds of elements. More specific classes inherit from Element.

Instance properties

Element inherits properties from its parent interface, Node, and by extension that interface's parent, EventTarget.

Instance methods

Element inherits methods from its parents Node, and its own parent, EventTarget.

  • element.computedStyleMap(). Returns a StylePropertyMapReadOnly interface which provides a read-only representation of a CSS declaration block that is an alternative to CSSStyleDeclaration.
  • element.getAttribute(). Returns the value of a specified attribute on the element.
  • element.getBoundingClientRect(). Returns the size of an element and its position relative to the viewport.
  • element.getClientRects(). Returns a collection of DOMRect objects that indicate the bounding rectangles for each CSS border box in a client.
  • element.hasAttribute(). Returns a Boolean value indicating whether the specified element has the specified attribute or not.
  • element.hasPointerCapture(). Checks whether the element on which it is invoked has pointer capture for the pointer identified by the given pointer ID.
  • element.scroll(). Scrolls to a particular set of coordinates inside a given element. (Note that this would be async in React Native.)
  • element.scrollBy(). Scrolls an element by the given amount. (Note that this would be async in React Native.)
  • element.scrollIntoView(). Scrolls the page until the element gets into the view. (Note that this would be async in React Native.)
  • element.scrollTo(). Alias for scroll().
  • element.setPointerCapture(). Used to designate a specific element as the capture target of future pointer events. Subsequent events for the pointer will be targeted at the capture element until capture is released.
  • element.releasePointerCapture(). Releases (stops) pointer capture that was previously set for a specific (PointerEvent) pointer.

Events

Listen to these events using addEventListener() or by assigning an event handler to the equivalent component prop.

  • error. Fired when a resource failed to load, or can't be used. For example, if a script has an execution error or an image can't be found or is invalid. Also available via the on-error property.
  • scroll. Fired when the document view or an element has been scrolled. Also available via the on-scroll property.
  • select. Fired when some text has been selected. Also available via the on-select property.
  • wheel. Fired when the user rotates a wheel button on a pointing device (typically a mouse). Also available via the on-wheel property.

Clipboard events

  • copy. Fired when the user initiates a copy action through the browser's user interface. Also available via the on-copy property.
  • cut. Fired when the user initiates a cut action through the browser's user interface. Also available via the on-cut prop.
  • paste. Fired when the user initiates a paste action through the browser's user interface. Also available via the on-paste prop.

Focus events

  • blur. Fired when an element has lost focus. Also available via the on-blur prop.
  • focus. Fired when an element has gained focus. Also available via the on-focus prop.
  • focusin. Fired when an element is about to gain focus.
  • focusout. Fired when an element is about to lose focus.

Keyboard events

  • keydown. Fired when a key is pressed. Also available via the on-keydown prop.
  • keyup. Fired when a key is released. Also available via the on-keyup prop.

Pointer events

  • auxclick. Fired when a non-primary pointing device button (e.g., any mouse button other than the left button) has been pressed and released on an element. Also available via the onAuxClick prop.
  • click. Fired when a pointing device button (e.g., a mouse's primary button) is pressed and released on a single element. Also available via the onClick prop.
  • contextmenu. Fired when the user attempts to open a context menu. Also available via the oncontextmenu property.
  • gotpointercapture. Fired when an element captures a pointer using setPointerCapture(). Also available via the on-gotpointercapture prop.
  • lostpointercapture. Fired when a captured pointer is released. Also available via the on-lostpointercapture prop.
  • pointercancel. Fired when a pointer event is canceled. Also available via the on-pointercancel prop.
  • pointerdown. Fired when a pointer becomes active. Also available via the on-pointerdown prop.
  • pointerenter. Fired when a pointer is moved into the hit test boundaries of an element or one of its descendants. Also available via the on-pointerenter prop.
  • pointerleave. Fired when a pointer is moved out of the hit test boundaries of an element. Also available via the on-pointerleave prop.
  • pointermove. Fired when a pointer changes coordinates. Also available via the on-pointermove prop.
  • pointerout. Fired when a pointer is moved out of the hit test boundaries of an element (among other reasons). Also available via the on-pointerout prop.
  • pointerover. Fired when a pointer is moved into an element's hit test boundaries. Also available via the on-pointerover prop.
  • pointerrawupdate. Fired when a pointer changes any properties that don't fire pointerdown or pointerup events.
  • pointerup. Fired when a pointer is no longer active. Also available via the on-pointerup prop.

HTMLElement

The HTMLElement interface represents any HTML element. Some elements directly implement this interface, while others implement it via an interface that inherits it.

Properties

Inherits properties from its parent, Element, and implements those from DocumentAndElementEventHandlers, GlobalEventHandlers, and TouchEventHandlers.

  • HTMLElement.hidden [Read only]. A boolean value indicating if the element is hidden or not.
  • HTMLElement.offsetHeight [Read only]. Returns a double containing the height of an element, relative to the layout.
  • HTMLElement.offsetLeft [Read only]. Returns a double, the distance from this element's left border to its offsetParent's left border.
  • HTMLElement.offsetParent [Read only]. Returns a Element that is the element from which all offset calculations are currently computed.
  • HTMLElement.offsetTop [Read only]. Returns a double, the distance from this element's top border to its offsetParent's top border.
  • HTMLElement.offsetWidth [Read only]. Returns a double containing the width of an element, relative to the layout.

Methods

Inherits methods from its parent, Element, and implements those from DocumentAndElementEventHandlers, GlobalEventHandlers, and TouchEventHandlers.

Events

Listen to these events using addEventListener() or by assigning an event listener to the equivalent component prop.

  • beforeinput. Fired when the value of an <input>, <select>, or <textarea> element is about to be modified.
  • change. Fired when the value of an <input>, <select>, or <textarea> element has been changed and committed by the user. Unlike the input event, the change event is not necessarily fired for each alteration to an element's value. Also available via the on-change property.
  • input. Fired when the value of an <input>, <select>, or <textarea> element has been changed. Also available via the on-input property.

HTMLDialogElement

The HTMLDialogElement interface represents an HTML <dialog> element, providing the properties and methods used to manipulate image elements.

Properties

Inherits properties from its parent, HTMLElement.

  • HTMLDialogElement.open. A boolean value representing the state of the open HTML attribute. true means it is set, and therefore the dialog is shown. false means it not set, and therefore the dialog is not shown.
  • HTMLDialogElement.returnValue. A string representing the returnValue of the dialog.

Methods

Inherits properties from its parent, HTMLElement.

  • HTMLDialogElement.close(). Closes the dialog. An optional string may be passed as an argument, updating the returnValue of the dialog.
  • HTMLDialogElement.show().Displays the dialog modelessly, i.e. still allowing interaction with content outside of the dialog.
  • HTMLDialogElement.showModal(). Displays the dialog as a modal, over the top of any other dialogs that might be present. Everything outside the dialog are inert with interactions outside the dialog being blocked.

Events

  • cancel. Also available via the on-cancel prop.
  • close. Also available via the on-close prop.

HTMLImageElement

The HTMLImageElement interface represents an HTML <img> element, providing the properties and methods used to manipulate image elements.

Properties

Inherits properties from its parent, HTMLElement.

  • HTMLImageElement.complete [Read only]. Returns a boolean value that is true if the browser has finished fetching the image, whether successful or not. That means this value is also true if the image has no src value indicating an image to load.
  • HTMLImageElement.currentSrc [Read only]. Returns a USVString representing the URL from which the currently displayed image was loaded. This may change as the image is adjusted due to changing conditions, as directed by any media queries which are in place.
  • HTMLImageElement.naturalHeight [Read only]. Returns an integer value representing the intrinsic height of the image in CSS pixels, if it is available; else, it shows 0. This is the height the image would be if it were rendered at its natural full size.
  • HTMLImageElement.naturalWidth [Read only]. An integer value representing the intrinsic width of the image in CSS pixels, if it is available; otherwise, it will show 0. This is the width the image would be if it were rendered at its natural full size.

Events

  • error. Also available via the on-error prop.
  • load. Also available via the on-load prop.

HTMLInputElement

The HTMLInputElement interface provides special properties and methods for manipulating the options, layout, and presentation of <input> elements.

Properties

Properties that apply only to visible elements containing text or numbers

  • disabled.
  • selectionEnd. unsigned long: Returns / Sets the end index of the selected text. When there's no selection, this returns the offset of the character immediately following the current text input cursor position.
  • selectionStart. unsigned long: Returns / Sets the beginning index of the selected text. When nothing is selected, this returns the position of the text input cursor (caret) inside of the element. (Resolves issue #35616.)
  • selectionDirection. string: Returns / Sets the direction in which selection occurred. Possible values are: forward (the selection was performed in the start-to-end direction of the current locale), backward (the opposite direction) or none (the direction is unknown).
  • value. string: Returns / Sets the current value of the control. If the user enters a value different from the value expected, this may return an empty string.

Methods

  • select(). Selects all the text in the input element, and focuses it so the user can subsequently replace all of its content.
  • setSelectionRange(). Selects a range of text in the input element (but does not focus it).
  • showPicker(). Shows a browser picker for date, time, color, and files.

Events

Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface:

  • invalid. Fired when an element does not satisfy its constraints during constraint validation. Also available via the on-invalid prop.
  • select event. Fired when some text has been selected.
  • selectionchange event. Fires when the text selection in a <input> element has been changed. Also available via the on-selectionchange prop.

HTMLTextAreaElement

The HTMLInputElement interface provides special properties and methods for manipulating the options, layout, and presentation of <input> elements.

Properties

  • disabled.
  • selectionEnd. unsigned long: Returns / Sets the end index of the selected text. When there's no selection, this returns the offset of the character immediately following the current text input cursor position.
  • selectionStart. unsigned long: Returns / Sets the beginning index of the selected text. When nothing is selected, this returns the position of the text input cursor (caret) inside of the <textarea> element.
  • selectionDirection. string: Returns / Sets the direction in which selection occurred. Possible values are: forward (the selection was performed in the start-to-end direction of the current locale), backward (the opposite direction) or none (the direction is unknown).
  • value. string: Returns / Sets the current value of the control. If the user enters a value different from the value expected, this may return an empty string.

Methods

  • select(). Selects all the text in the input element, and focuses it so the user can subsequently replace all of its content.
  • setSelectionRange(). Selects a range of text in the input element (but does not focus it).

Events

Listen to these events using addEventListener() or using the equivalent prop name.

  • select event. Fired when some text has been selected.
  • selectionchange event. Fires when the text selection in a <input> element has been changed. Also available via the on-selectionchange prop.

Components API (React DOM subset)

Support a subset of React DOM components directly. Exported as an html object, i.e., html.div, html.a, etc.

This would provide a built-in declarative API for cross-platform elements in React Native. All unknown tags default to <span> layout. All known-but-unimplemented block-level tags default to <div> layout.

Sections

Content sectioning elements allow you to organize the document content into logical pieces. Use the sectioning elements to create a broad outline for your page content, including header and footer navigation, and heading elements to identify sections of content.

Text

Text content elements organize blocks or sections of content. Important for accessibility, these elements identify the purpose or structure of that content.

Inline text

Inline text semantics define the meaning, structure, or style of a word, line, or any arbitrary piece of text.

Media

  • img is similar to Image without advanced loader configuration.

Forms

Elements which can be used together to create forms which the user can fill out and submit. There's a great deal of further information about this available in the HTML forms guide.


Props API (React DOM subset)

Support a subset of React DOM props.

Common props

Props supported on all elements.

Supporting the ARIA 1.2 interface would allow more ARIA-targeting React DOM libraries to work on React Native, and would provide a well defined cross-platform target for equivalent native features (e.g., React Native for Windows needing heading levels, set size, etc.)

Common events

Events supported on all elements.

Each event handler should receive a W3C event object of the corresponding type, not a synthetic event. These props are merely conveniences and otherwise identical to using the EventTarget API mentioned later on. Note that no capture phase props are included, as listening to the capture phase (as well as custom events) can be handled with the EventTarget API. (Alternatively, we introduce oncapture-click, etc.)

To avoid breaking changes in React Native and React DOM, it may be preferrable to create new event prop names that receive events as specified by web standards, e.g., on-click, on-pointerup.

Resolves proposal #492.

  • on-auxclick is a PointerEvent for auxillary clicks.
  • on-blur.
  • on-click is a PointerEvent for primary clicks.
  • on-contextmenu is a PointerEvent for context clicks / long press.
  • on-copy.
  • on-cut.
  • on-focus.
  • on-gotpointercapture.
  • on-lostpointercapture.
  • on-paste.
  • on-pointercancel.
  • on-pointerdown.
  • on-pointerenter.
  • on-pointerleave.
  • on-pointermove.
  • on-pointerout.
  • on-pointerover.
  • on-pointerup.
  • on-keydown.
  • on-keyup.

<a> props

Additional props for <a>.

  • download.
  • href. Clicking will always attempt to open the URL in a browser, mail client, etc. Use of e.preventDefault() in an event handler will disable this behavior and allow custom routing logic to handle the interaction.
  • referredPolicy.
  • rel.
  • target.

<dailog> props

Additional props for <dialog>.

<img> props

Additional props for <img>.

  • alt prop for alternative text support.
  • crossOrigin is equivalent to setting the relevant Header in the source object. Declaratively configure cross-origin permissions for loaded images.
  • decoding.
  • draggable.
  • fetchPriority.
  • height is the same as source.height.
  • loading.
  • referrerPolicy is equivalent to setting the relevant Header in the source object. Declaratively configure referrer policy.
  • src is the same as source.uri.
  • srcSet is the same as setting a source array with uri and scale properties defined.
  • width is the same as source.width.

<img> events

Additional events for <img>.

<input> props

Additional props for <input>.

  • autoComplete is the same as mapped values for existing autoComplete (Android) and textContentType (iOS).
  • disabled.
  • enterKeyHint is the same as mapped values for returnKeyType.
  • inputMode is the same as mapped values for keyboardType.
    • inputMode === 'decimal' is the same as keyboardType = 'decimal-pad'.
    • inputMode === 'email' is the same as keyboardType = 'email-address'.
    • inputMode === 'none' is the same as showSoftInputOnFocus = false.
    • inputMode === 'numeric' is the same as keyboardType = 'numeric'.
    • inputMode === 'search' is the same as keyboardType = 'search'.
    • inputMode === 'tel' is the same as keyboardType = 'phone-pad'.
    • inputMode === 'url' is the same as keyboardType = 'url'.
  • max.
  • maxLength.
  • min.
  • minLength.
  • placeholder.
  • readOnly is the same as inverse editable.
  • required.
  • spellCheck.
  • type.
  • value.

<textarea> props

Additional props for <textarea>.

  • autoComplete is the same as mapped values for existing autoComplete (Android) and textContentType (iOS).
  • disabled.
  • enterKeyHint is the same as mapped values for returnKeyType.
  • inputMode is the same as mapped values for keyboardType.
    • inputMode === 'decimal' is the same as keyboardType = 'decimal-pad'.
    • inputMode === 'email' is the same as keyboardType = 'email-address'.
    • inputMode === 'none' is the same as showSoftInputOnFocus = false.
    • inputMode === 'numeric' is the same as keyboardType = 'numeric'.
    • inputMode === 'search' is the same as keyboardType = 'search'.
    • inputMode === 'tel' is the same as keyboardType = 'phone-pad'.
    • inputMode === 'url' is the same as keyboardType = 'url'.
  • max.
  • maxLength.
  • min.
  • minLength.
  • placeholder.
  • readOnly is the same as inverse editable.
  • required.
  • rows is the same as numberOfLines.
  • spellCheck.
  • value.

<input> and <textarea> events

Additional events for <input> and <textarea>.

  • on-beforeinput
  • on-change
  • on-input
  • on-invalid
  • on-select
  • on-selectionchange

Styles API (CSS subset)

Significantly expanded styling capabilities to cover more of the features that are heavily relied upon by web engineers. Styles are used with the css.create() function and are passed to the style prop on elements.

css() function

Styles must be wrapped in css().

const styles = css.create({
  foo: {
    width: 100
  },
  bar: (color) => ({
    color
  })
});

<div style={styles.foo} />
<div style={styles.bar(props.color)} />

CSS Compatibility

Existing properties that can be adjusted to align with the CSS spec.

  • aspectRatio. Support string values, i.e., '16 / 9', to align with CSS.
  • borderRadius. Support percentage values to align with CSS.
  • fontVariant support space-separated string values to align with CSS.
  • fontWeight support number values to align with React DOM / CSS.
  • objectFit is equivalent to resizeMode for <Image>.
  • pointerEvents is equivalent to pointerEvents prop.
  • position. Support for fixed and sticky values.
  • transform. Support using string values to set transforms.
  • verticalAlign is equivalent to textAlignVertical.
  • userSelect. Equivalent to using selectable prop on <Text>.

Existing logical properties that can be adjusted to adopt the CSS standard names. In addition, React Native will need to add native support for subtree-level writing direction controls. Setting the dir prop (or direction style) to ltr or rtl on an element should alter the way logical properties are resolved in the subtree.

  • (direction. But it is not recommended for most use cases on web.)
  • borderEndEndRadius is equivalent to borderBottomEndRadius.
  • borderEndStartRadius is equivalent to borderBottomStartRadius.
  • borderStartEndRadius is equivalent to borderTopEndRadius.
  • borderStartStartRadius is equivalent to borderTopStartRadius.
  • borderBlockColor is equivalent to borderTopColor & borderBottomColor.
  • borderBlockEndColor is equivalent to borderBottomColor.
  • borderBlockStartColor is equivalent to borderTopColor.
  • borderInlineColor is equivalent to borderEndColor & borderStartColor.
  • borderInlineEndColor is equivalent to borderEndColor.
  • borderInlineStartColor is equivalent to borderStartColor.
  • borderBlockStyle is equivalent to borderTopStyle & borderBottomStyle.
  • borderBlockEndStyle is equivalent to borderBottomStyle.
  • borderBlockStartStyle is equivalent to borderTopStyle.
  • borderInlineStyle is equivalent to borderEndStyle & borderStartStyle.
  • borderInlineEndStyle is equivalent to borderEndStyle.
  • borderInlineStartStyle is equivalent to borderStartStyle.
  • borderBlockWidth is equivalent to borderTopWidth & borderBottomWidth.
  • borderBlockEndWidth is equivalent to borderBottomWidth.
  • borderBlockStartWidth is equivalent to borderTopWidth.
  • borderInlineWidth is equivalent to borderEndWidth & borderStartWidth.
  • borderInlineEndWidth is equivalent to borderEndWidth.
  • borderInlineStartWidth is equivalent to borderStartWidth.
  • marginInlineStart is equivalent to marginStart.
  • marginInlineEnd is equivalent to marginEnd.
  • marginBlockStart is equivalent to marginTop.
  • marginBlockEnd is equivalent to marginBottom.
  • marginBlock is equivalent to marginVertical.
  • marginInline is equivalent to marginHorizontal.
  • paddingInlineStart is equivalent to paddingStart.
  • paddingInlineEnd is equivalent to paddingEnd.
  • paddingBlockStart is equivalent to paddingTop.
  • paddingBlockEnd is equivalent to paddingBottom.
  • paddingBlock is equivalent to paddingVertical.
  • paddingInline is equivalent to paddingHorizontal.
  • inset is equivalent to top & bottom & right & left.
  • insetBlock is equivalent to top & bottom.
  • insetBlockEnd is equivalent to bottom.
  • insetBlockStart is equivalent to top.
  • insetInline is equivalent to right & left.
  • insetInlineEnd is equivalent to right or left.
  • insetInlineStart is equivalent to right or left.
  • blockSize is equivalent to height.
  • minBlockSize is equivalent to minHeight.
  • maxBlockSize is equivalent to maxHeight.
  • inlineSize is equivalent to width.
  • minInlineSize is equivalent to minWidth.
  • maxInlineSize is equivalent to maxWidtht.

CSS Animations

Support declarative keyframes and animations that can be optimized on the native side and avoid the need for Animated. Consider dispatching the corresponding W3C animation events too. See animation).

TBD: the relationship between animationName (or equivalent) and the API used to define Animation keyframes.

CSS Colors

Support CSS 4 Colors, possibly by using Colorjs.io or implementing a native equivalent.

CSS Container Queries

Prepare for CSS Container Queries.

CSS Custom Properties

Support CSS custom property syntax --variable-name. This could be shimmed in user-space on top of the existing StyleSheet API, with a React Context used to provide variables and values to a subtree.

CSS Filters

Support declarative filters as used by the CSS filter style.

CSS Functions

CSS Lengths

Support major units where supported by CSS.

  • em units.
  • rem units.
  • px units.
  • v* units.
  • % units.

CSS Media Queries

Support CSS Media Queries.

Although Media Queries are not a preferred long-term solution for responsive design, Container Queries are not yet widely supported by browsers. The dimensional Media Queries could be shimmed in user-space on top of the existing StyleSheet API.

Logical operators not, and, or, only.

Media features:

Proposed syntax:

// Either
css.create({
  position: 'absolute',
  '@media (max-width: 600px)': {
    position: 'sticky',
  }
});

// Or
css.create({
  position: {
    default: 'absolute',
    '@media (max-width: 600px)': 'sticky',
  }
});

The benefit of the latter is clearer expectations (and greater constraints) about when properties are overridden. For example, it's not as clear what the value for position would be in the following:

css.create(
  {
    position: 'absolute',
    '@media (max-width: 600px)': {
      position: 'sticky',
    }
  },
  {
    position: 'relative',
  }
);

// {
//   position: relative,
//   '@media (max-width: 600px)': {
//     position: 'sticky',
//   }
// }

Whereas in the next example we can set expectations that a property and any previous conditions are completed overridden by any declaration that later modifies the property in any way.

css.create(
  {
    position: {
      default: 'absolute',
      '@media (max-width: 600px)': 'sticky'
    }
  },
  {
    position: {
      default: 'relative',
    }
  }
);

// {
//   position: relative
// }

Consideration is also required to determine what the final value of a property is when Media Query conditions overlap, i.e., which media features and which conditions (e.g., multiple width conditions) take priority over others.

CSS Properties and Values

Miscellaneous CSS properties and values that should be supported on native.

CSS Transitions

Support declarative transitions that can be optimized on the native side and avoid the need for Animated. Consider dispatching the corresponding W3C transition events too.