diff --git a/docs/404.html b/docs/404.html new file mode 100644 index 00000000..c9ebf1d2 --- /dev/null +++ b/docs/404.html @@ -0,0 +1 @@ +404 // React Native for Web

404

\ No newline at end of file diff --git a/docs/docs/about-project/index.html b/docs/docs/about-project/index.html new file mode 100644 index 00000000..6dfc5ba3 --- /dev/null +++ b/docs/docs/about-project/index.html @@ -0,0 +1,3 @@ +About the project // React Native for Web

About the project

React Native for Web’s origins, evolution, and development.

React Native for Web was started in 2015 by Nicolas Gallagher during the development of Twitter’s Progressive Web App. It has evolved from a framework inspired by React Native into a mature and pragmatic compatibility layer between React DOM and React Native.

React Native for Web is currently used in production Web apps by companies including Twitter, Flipkart, Uber, and Major League Soccer. Software engineers from Facebook, Twitter, and Expo continue to contribute design and patches to the project.

Developing a Web compatibility layer for React Native involves balancing the needs of high-quality Web apps with the value of React Native API compatibility. There are instances where parts of the React Native API are co-opted to infer information that is necessary or beneficial to products running in Web browsers. Other times there are use cases that are not accomodated by the APIs provided; even when that information cannot be pragmatically incorporated into the existing React Native API design constraints, it still helps to inform which API changes are needed over the long term.

The evolution of React Native now involves developers who work on React Native for Android, iOS, Web, Windows, and macOS. We aim to help designers and developers with shared, platform-agnostic React APIs that reduce time to market for high-quality, multi-platform products.

Please browse the source code and consider contributing your experience to the project.

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/accessibility/index.html b/docs/docs/accessibility/index.html new file mode 100644 index 00000000..187d32b1 --- /dev/null +++ b/docs/docs/accessibility/index.html @@ -0,0 +1,3 @@ +Accessibility // React Native for Web

Accessibility

Familiar web accessibility APIs in a platform-agnostic form.

Accessibility in React Native for Web combines several separate web APIs into a cohesive system. Assistive technologies (e.g., VoiceOver, TalkBack screen readers) derive useful information about the structure, purpose, and interactivity of web apps from their HTML elements, attributes, and ARIA in HTML.


Accessibility Props API #

React Native for Web includes APIs for making accessible apps. The most common and well supported accessibility features of the Web are exposed as platform-agnostic accessibility* props.

accessibilityActiveDescendant ?string

Equivalent to aria-activedescendant.

accessibilityAtomic ?boolean

Equivalent to aria-atomic.

accessibilityAutoComplete ?string

Equivalent to aria-autocomplete.

accessibilityBusy ?boolean

Equivalent to aria-busy.

accessibilityChecked ?(boolean | "mixed")

Equivalent to aria-checked.

accessibilityColumnCount ?number

Equivalent to aria-colcount.

accessibilityColumnIndex ?number

Equivalent to aria-colindex.

accessibilityColumnSpan ?number

Equivalent to aria-colspan.

accessibilityControls ?string

Equivalent to aria-controls.

accessibilityDescribedBy ?string

Equivalent to aria-describedby.

accessibilityDetails ?string

Equivalent to aria-details.

accessibilityDisabled ?boolean

Equivalent to aria-disabled.

accessibilityErrorMessage ?string

Equivalent to aria-errormessage.

accessibilityExpanded ?boolean

Equivalent to aria-expanded.

accessibilityFlowTo ?string

Equivalent to aria-flowto.

accessibilityHasPopup ?string

Equivalent to aria-haspopup.

accessibilityHidden ?boolean

Equivalent to aria-hidden.

accessibilityInvalid ?boolean

Equivalent to aria-invalid.

accessibilityKeyShortcuts ?Array<string>

Equivalent to aria-keyshortcuts.

accessibilityLabel ?string

Equivalent to aria-label.

accessibilityLabelledBy ?string

Equivalent to aria-labelledby.

accessibilityLiveRegion ?("assertive" | "off" | "polite")

Equivalent to aria-live.

accessibilityModal ?boolean

Equivalent to aria-modal.

accessibilityMultiline ?boolean

Equivalent to aria-multiline.

accessibilityMultiSelectable ?boolean

Equivalent to aria-multiselectable.

accessibilityOrientation ?("horizontal" | "vertical")

Equivalent to aria-orientation.

accessibilityOwns ?string

Equivalent to aria-owns.

accessibilityPlaceholder ?string

Equivalent to aria-placeholder.

accessibilityPosInSet ?number

Equivalent to aria-posinset.

accessibilityPressed ?boolean

Equivalent to aria-pressed.

accessibilityReadOnly ?boolean

Equivalent to aria-readonly.

accessibilityRequired ?boolean

Equivalent to aria-required.

accessibilityRole ?boolean

Equivalent to role.

accessibilityRoleDescription ?string

Equivalent to aria-roledescription.

accessibilityRowCount ?number

Equivalent to aria-rowcount.

accessibilityRowIndex ?number

Equivalent to aria-rowindex.

accessibilityRowSpan ?number

Equivalent to aria-rowspan.

accessibilitySelected ?boolean

Equivalent to aria-selected.

accessibilitySetSize ?number

Equivalent to aria-setsize.

accessibilitySort ?("ascending" | "descending" | "none" | "other")

Equivalent to aria-sort.

accessibilityValueMax ?number

Equivalent to aria-valuemax.

accessibilityValueMin ?number

Equivalent to aria-valuemin.

accessibilityValueNow ?number

Equivalent to aria-valuenow.

accessibilityValueText ?string

Equivalent to aria-valuetext.


Accessibility patterns #

The Text and View components can be rendered as links. If the href prop is set, the element will render <a> tags without altering the presentation of the element.

<Text href="/" />
// <a href="/" ></a>

The hrefAttrs prop sets link-related attributes.

const hrefAttrs = { download: true, rel: "nofollow", target: "blank" };

<Text
href="/document.pdf"
hrefAttrs={hrefAttrs}
/>

// <a download href="/document.pdf" rel="nofollow" target="_blank"></a>

Keyboard focus #

The focusable prop determines whether a component is user-focusable and appears in the keyboard tab flow. This prop should be used instead of the accessible prop found in React Native for Android/iOS, which is not implemented by React Native for Web/Windows/macOS.

<View focusable={true} />
// <div tabindex="0"></div>

<Text focusable={false} href="/" />
// <a href="/" tabindex="-1"></a>

Did you know? Any element (including elements not in the keybaord tab flow) can be programmatically focused from its ref: viewRef.current.focus().

Accessible HTML #

React Native for Web components express semantics exclusively via the accessibility* props which are equivalent to aria-* attributes. For example, accessibilityRole is equivalent to the HTML role attribute, accessibilityLabel is equivalent to aria-label, etc. (Additional compatibility with React Native accessibility props is also included.)

<View
accessibilityLabel="..."
accessibilityPressed={false}
accessibilityRole="menuitem"
nativeID="abc"
/>

/*
<div
aria-label="..."
aria-pressed="false"
id="abc"
role="menuitem"
/>
*/

Semantic HTML #

The value of the accessibilityRole prop is used to infer an analogous HTML element where appropriate. This is done to rely on well-supported native mechanisms for encoding semantics and accessibility information.

<View accessibilityRole="article">
<Text accessibilityRole="paragraph">This is an article</Text>
</View>
/*
<article>
<div role="paragraph">This is an article</div>
</article>
*/

The "paragraph" role isn’t mapped to a <p> tag because it’s an HTML conformance error to include block-level children within the element; both Text and View support block-level children.

If the "heading" role is combined with an accessibilityLevel, the equivalent HTML heading element is rendered. Otherwise, it is rendered as <h2>.

<Text accessibilityRole="heading" /> /* <h2> */
<Text accessibilityRole="heading" accessibilityLevel={1} /> /* <h1> */

Note: Avoid changing accessibilityRole values over time or after user actions. Generally, accessibility APIs do not provide a means of notifying assistive technologies if a role changes.

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/activity-indicator/index.html b/docs/docs/activity-indicator/index.html new file mode 100644 index 00000000..36a44523 --- /dev/null +++ b/docs/docs/activity-indicator/index.html @@ -0,0 +1,3 @@ +ActivityIndicator // React Native for Web

ActivityIndicator

Displays a customizable activity indicator.

import { ActivityIndicator } from 'react-native';

<ActivityIndicator {...props} />;

API #

Props #

...ViewProps ?ViewProps

All the props supported by View.

animating ?boolean

Default true. Set whether the activity indicator is animating.

color ?string

Default "#1976D2". Set the color of the activity indicator.

hidesWhenStopped ?boolean

Default true. Set whether the activity indicator is hidden when not animating.

size ?("small" | "large" | number)

Default "small". Set the size of the activity indicator.


Examples #

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/animated/index.html b/docs/docs/animated/index.html new file mode 100644 index 00000000..d9b25b41 --- /dev/null +++ b/docs/docs/animated/index.html @@ -0,0 +1,3 @@ +Animated // React Native for Web

Animated

Animated focuses on declarative relationships between inputs and outputs, configurable transforms in between, and start/stop methods to control time-based animation execution.

This API is the same JavaScript implementation as found in React Native. Please refer to the React Native documentation below:

Warning! The React Native animation API is not optimized for the web. You may prefer to use external modules that are designed for multi-platform animations and provide better performance, e.g., React Spring.

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/app-registry/index.html b/docs/docs/app-registry/index.html new file mode 100644 index 00000000..23e8e65d --- /dev/null +++ b/docs/docs/app-registry/index.html @@ -0,0 +1,3 @@ +AppRegistry // React Native for Web

AppRegistry

AppRegistry is the control point for registering, running, prerendering, and unmounting all apps.

App root components should register themselves with AppRegistry.registerComponent. Apps can be run by invoking AppRegistry.runApplication.

import { AppRegistry } from 'react-native';

API #

Static methods #

getAppKeys () => Array<string>

Returns an array of all registered app keys

getApplication (key: string, params: AppParams) => ({ element, getStyleElement })

A web-only method for server-side rendering to HTML and CSS. It returns an object containing the given application’s element and getStyleElement function to get styles once the element is rendered.

registerComponent (key: string, getComponent: () => React.Element) => void

Register a component provider under the given key.

registerConfig (configs: Array<AppConfig>) => void

Register multiple applications.

unmountApplicationComponentAtRootTag rootTag: HTMLElement

Called this function with the rootTag that was passed into runApplication in order to unmount it.

AppConfig #

appKey string

The key under which the component is registered.

component () => React.Element

A function that returns a React element.

AppParams #

callback ?() => void

Called when React rendering has finished.

hydrate ?boolean

If the client should hydrate server-rendered HTML.

initialProps ?Object

The initial props passed to the root component.

rootTag HTMLElement

The native element into which the application is rendered.

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/app-state/index.html b/docs/docs/app-state/index.html new file mode 100644 index 00000000..69f1b7a8 --- /dev/null +++ b/docs/docs/app-state/index.html @@ -0,0 +1,3 @@ +AppState // React Native for Web

AppState

AppState can tell you if the app is in the foreground or background, and notify you when the state changes.

States: active (the app is running in the foreground), background (the app is running in the background, i.e., the user has not focused the app’s tab).

import { AppState } from 'react-native';

API #

Static properties #

isAvailable boolean

Whether the browser environment supports AppState.

currentState ?("active" | "background")

Returns the current state of the app.

Static methods #

addEventListener (type: ?string, listener: (boolean) => void) => void

Add a listener to AppState changes. Listen to the "change" event type. The handler is called with the app state value.

removeEventListener (type: ?string, listener: (boolean) => void) => void

Remove a listener from AppState changes.


Examples #

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/appearance/index.html b/docs/docs/appearance/index.html new file mode 100644 index 00000000..36aa44f3 --- /dev/null +++ b/docs/docs/appearance/index.html @@ -0,0 +1,3 @@ +Appearance // React Native for Web

Appearance

The Appearance module exposes information about the user’s appearance preferences, such as their preferred color scheme (light or dark).

import { Appearance } from 'react-native';

API #

Static methods #

getColorScheme () => ("dark" | "light")

You can use the Appearance module to determine if the user prefers a dark color scheme. Although the color scheme is available immediately, this may change (e.g. scheduled color scheme change at sunrise or sunset). Any rendering logic or styles that depend on the user preferred color scheme should try to call this function on every render, rather than caching the value.

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/browser-compatibility/index.html b/docs/docs/browser-compatibility/index.html new file mode 100644 index 00000000..01db319f --- /dev/null +++ b/docs/docs/browser-compatibility/index.html @@ -0,0 +1,3 @@ +Browser compatibility // React Native for Web

Browser compatibility

Understanding React Native for Web browser compatibility.

React Native for Web is designed and tested for recent mobile and desktop browsers, for touch and mouse and keyboard interactions.

The browsers with known support include:

  • Chrome 60+
  • Safari 10+ / iOS Safari 10+
  • Edge 12+
  • Firefox ESR+
  • Internet Explorer 11
  • Opera

If specific exports have a different browser support expectation, it will be documented with that export.


JavaScript #

Your application may need to polyfill Promise, Object.assign, Array.from, and ResizeObserver as necessary for your desired browser support.


CSS #

Most CSS properties and values are supported. Vendor prefixes are automatically provided where necessary. For example, if you use the following style:

const style = {
userSelect: 'none'
}

The resulting CSS is:

.r-userSelect-24jds {
-webkit-user-select: none;
user-select: none;
}

Certain CSS properties are not supported across all browsers, but are polyfilled by React Native for Web.

(N.B. Safari prior to version 10.1 can suffer from extremely poor flexbox performance. The recommended way to work around this issue (as used on mobile.twitter.com) is to set display:block on Views in your element hierarchy that you know don’t need flexbox layout.)

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/button/index.html b/docs/docs/button/index.html new file mode 100644 index 00000000..bac8701f --- /dev/null +++ b/docs/docs/button/index.html @@ -0,0 +1,3 @@ +Button // React Native for Web

Button

A basic button component. Supports a minimal level of customization.

You can also build a custom button using Pressable.

import { Button } from 'react-native';

<Button {...props} />;

API #

Props #

accessibilityLabel ?string

Equivalent to aria-label.

color ?string

Default "#2196F3". Set the background color of the button.

disabled ?boolean

Prevent all interactions with the button.

onPress ?(e: ClickEvent) => void

Called when the button is pressed by a pointer or keyboard.

testID ?string

Set the test selector label (via data-testid).

title string

Set the text content of the button.


Examples #

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/checkbox/index.html b/docs/docs/checkbox/index.html new file mode 100644 index 00000000..7d5d999c --- /dev/null +++ b/docs/docs/checkbox/index.html @@ -0,0 +1,3 @@ +CheckBox // React Native for Web

CheckBox

An accessible checkbox component with customizable appearance.

CheckBox is a controlled component. The onValueChange callback should be used to update the value prop to reflect user actions. If the value prop is not updated, the component will continue to render the supplied value prop instead of the expected result of any user actions.

import { CheckBox } from 'react-native-web';

<CheckBox {...props} />;

API #

Props #

...ViewProps ?ViewProps

All the props supported by View.

color ?string = "#AAB8C2"

Set the background color of the checkbox.

disabled ?boolean

Prevent all interactions with the checkbox.

onChange ?(e: ChangeEvent) => void

Called when the state of the native checkbox changes.

onValueChange ?(value: boolean | "mixed") => void

Called when the state of the native checkbox changes.

value ?(boolean | "mixed") = false

Set the value of the checkbox.


Examples #

Note that the size of the checkbox can be controlled by changing the height and width style properties.

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/clipboard/index.html b/docs/docs/clipboard/index.html new file mode 100644 index 00000000..5973975f --- /dev/null +++ b/docs/docs/clipboard/index.html @@ -0,0 +1,3 @@ +Clipboard // React Native for Web

Clipboard

Clipboard gives you an interface for setting to the clipboard. (Getting clipboard content is not currently supported on web.)

import { Clipboard } from 'react-native';

API #

Static methods #

isAvailable () => boolean

Determines whether the browser environment supports Clipboard at all.

setString () => boolean

Copies a string to the clipboard. On web, some browsers may not support copying to the clipboard, therefore, this function returns a boolean to indicate if the copy was successful.

getString () => Promise<"">

Not properly supported on Web. Returns a Promise of an empty string.


Examples #

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/dimensions/index.html b/docs/docs/dimensions/index.html new file mode 100644 index 00000000..1edbe93b --- /dev/null +++ b/docs/docs/dimensions/index.html @@ -0,0 +1,3 @@ +Dimensions // React Native for Web

Dimensions

Respond to changes in the viewport dimensions.

Dimensions may change (e.g., due to device rotation) so any rendering logic or styles that depend on these constants should try to call this function on every render, rather than caching the value.

import { Dimensions } from 'react-native';

API #

Static methods #

get (string: "window" | "screen") => Dimension

Get a dimension (e.g., window or screen).

set (dimensions: { window: Dimension, screen: Dimension }) => void

This should only be called server-side with an estimate for initial dimensions to be used when pre-rendering pages on the server.

addEventListener (type: ?string, listener: (dimensions) => void) => void

Add a listener to Dimensions changes. Listen to the "change" event type. The handler is called with the dimensions state.

removeEventListener (type: ?string, listener: (dimensions) => void) => void

Remove a listener from Dimensions changes.

Dimension #

height number

The height of the dimension.

width number

The width of the dimension.


Examples #

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/help/index.html b/docs/docs/help/index.html new file mode 100644 index 00000000..543cd1a6 --- /dev/null +++ b/docs/docs/help/index.html @@ -0,0 +1,3 @@ +Help // React Native for Web
\ No newline at end of file diff --git a/docs/docs/i18n-manager/index.html b/docs/docs/i18n-manager/index.html new file mode 100644 index 00000000..d7a1964c --- /dev/null +++ b/docs/docs/i18n-manager/index.html @@ -0,0 +1,3 @@ +I18nManager // React Native for Web

I18nManager

Control and query the layout and writing direction of the application.

import { I18nManager } from 'react-native';

API #

Static methods #

allowRTL (boolean) => void

Allow the application to display in RTL mode.

forceRTL (boolean) => void

Force the application to display in RTL mode.

getConstants () => I18nConstants

Determine how the application is handling bidi layout.

swapLeftAndRightInRTL (boolean) => void

Control whether the application swaps left/right styles in RTL mode. It is recommended that applications rely on start/end styles and disable automatic BiDi-flipping of left/right styles.

setPreferredLanguageRTL (boolean) => void

Set the application’s preferred writing direction to RTL. You may need to infer the user’s preferred locale on the server (from HTTP headers) and decide whether it’s an RTL language. (Web-only)

I18nConstants #

The object returned by I18nManager.getConstants().

isRTL boolean = false

Whether the application is currently in RTL mode.

doLeftAndRightSwapInRTL boolean = true

Whether the application swaps left/right styles in RTL mode.


Examples #

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/image-background/index.html b/docs/docs/image-background/index.html new file mode 100644 index 00000000..d0c5939e --- /dev/null +++ b/docs/docs/image-background/index.html @@ -0,0 +1,3 @@ +ImageBackground // React Native for Web

ImageBackground

An image component with support for child content.

import { ImageBackground } from 'react-native';

<ImageBackground {...props}>{children}</ImageBackground>;

API #

Props #

...ImageProps ?ImageProps

All the props supported by Image.

children ?any

Content to display over the image.

imageStyle ?Style

Styles to forward to the image component.

Examples #

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/image/index.html b/docs/docs/image/index.html new file mode 100644 index 00000000..1fc70376 --- /dev/null +++ b/docs/docs/image/index.html @@ -0,0 +1,3 @@ +Image // React Native for Web

Image

An accessible and responsive image component.

This component renders images with flexbox layout and cover object-fit (rather than stretch) by default.

import { Image } from 'react-native';

<Image {...props} />;

API #

Props #

...ViewProps ?ViewProps

All the props supported by View.

blurRadius ?number

The radius of the blur filter added to the image

defaultSource ?Source

A static image to display while loading the image source.

draggable ?boolean = false

Set whether the image can be dragged with native browser behavior. (Web-only)

onError ?({ nativeEvent: { error } }) => void

Called when the image fails to load.

onLoad ?({ nativeEvent: LoadEvent ) => void

Called when the image successfully loads.

onLoadEnd ?() => void

Called when image loading ends.

onLoadStart ?() => void

Called when the image loading starts.

resizeMode ?("center" | "cover" | "contain" | "none" | "stretch") = "cover"

The image source. The string can be a path to an external resource or a base64 encoded resource.

source ?(string | Source)

The image source. The string can be a path to an external resource or a base64 encoded resource.

Source

height ?number

Set the styles of the view.

uri ?string

Set the styles of the view.

width ?number

Set the styles of the view.

Statics #

getSize ?(url: string, complete, failure) => void

Download an image and measure the width and height (in pixels) prior to displaying it. This method can fail if the image cannot be found, or fails to download.
Complete callback: (width: number, height: number) => void.
Failure callback: () => void.

prefetch ?(url: string) => Promise

Prefetches a remote image for later use by downloading it. Once an image has been prefetched it is assumed to be in native browser caches and available for immediate rendering.

queryCache ?(urls: Array<string>) => Promise

Performs cache interrogation. Returns a mapping from URL to cache status: “disk”, “memory”, “disk/memory”. If a requested URL is not in the mapping, it means it’s not in the cache.


Examples #

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/index.html b/docs/docs/index.html new file mode 100644 index 00000000..d9d136a5 --- /dev/null +++ b/docs/docs/index.html @@ -0,0 +1,3 @@ +Introduction to React Native for Web // React Native for Web

Introduction to React Native for Web

React Native for Web is a compatibility layer between React DOM and React Native. It can be used in new and existing apps, web-only and multi-platform apps.

React Native for Web uses React DOM to accurately render React Native compatible JavaScript code in a web browser. This brings several powerful abstractions to web developers include a simple styles in JavaScript API, built-in layout localization, and a high-level gesture system.

Modern React #

React Native for Web is made with modern React APIs including function components and hooks. It builds upon React DOM, making it straight-forward for React DOM apps to incrementally adopt the framework (as was done by Twitter and Flipkart.) The project aims to provide broad compatibility with React alternatives, but will continue to evolve with React as APIs like Concurrent Mode and Server Components are introduced.

Modern Web #

React Native for Web makes direct use of native DOM APIs to implement specific features. As the Web platform improves, so does React Native for Web. Although certains APIs in the project have remained unchanged since inception, the implementations have become smaller and faster by migrating to new DOM APIs as they became broadly available in browsers.

Components #

React Native for Web provides all the core components you’d expect from React Native. You will mostly work with View, Image, Text, TextInput, and ScrollView. The core components include props for working with interactions, including the advanced gesture responder system. Each component’s documentation contains live and editable examples to try out.

React Native for Web exports many different modules to support a variety of use cases. Your application can use as many or as few of these modules as needed. The babel plugin will help you to only bundle the modules that you are using.

Styles #

React Native for Web components use JavaScript to author styles which are converted to native CSS. The design of this styling system avoids all the problems with CSS at scale and produces highly optimized CSS without the need to learn a domain-specific styling language and without the need for specialized tooling that parses markup to remove unused styles.

Reliable and tested #

React Native for Web is thoroughly unit and production tested. Significant changes are first published as canary releases to limit regressions and gather feedback from partners. Pull requests record changes to the compressed file size of each module in the library.

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/installation/index.html b/docs/docs/installation/index.html new file mode 100644 index 00000000..8704a4d4 --- /dev/null +++ b/docs/docs/installation/index.html @@ -0,0 +1,3 @@ +Installation // React Native for Web

Installation

An overview of how to install and use React Native for Web.

React Native for Web can be used for multi-platform and web-only applications. It can be incrementally adopted by existing React Web apps and integrated with existing React Native apps. Preact is also supported.

npm install react-dom react-native-web

The Babel plugin is recommended for build-time optimizations.

npm install --save-dev babel-plugin-react-native-web

Quickstart #

Expo #

Expo is a framework and a platform for universal React applications. Expo for Web uses React Native for Web, provides dozens of additional cross-platform APIs, includes web build optimizations, and is compatibile with the broder React Native ecosystem.

npx expo-cli init my-app
cd my-app
npm install react-dom react-native-web
npx expo-cli start

Create React App #

Create React App is a basic way to setup a simple, web-only React app with built-in support for aliasing react-native-web to react-native. However, it’s generally recommended that you use Expo.

npx create-react-app my-app
cd my-app
npm install react-native-web
npm start

Integrations #

Visit the React Native Directory to find React Native packages with known web support. Popular web frameworks maintain example integrations.

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/interactions/index.html b/docs/docs/interactions/index.html new file mode 100644 index 00000000..c812c4de --- /dev/null +++ b/docs/docs/interactions/index.html @@ -0,0 +1,3 @@ +Interactions // React Native for Web

Interactions

Interactions and gestures for the web.

React Native for Web extends the interaction modes available in React Native to account for mouse, touch, and keyboard use. The Responder System is available for more advanced gesture recognition.


Click Props API #

Click interactions are available on supporting elements. These events are React DOM synthetic mouse events. The click events may be dispatched by the browser following user interactions with a pointer (mouse or touch) as well as a keyboard.

In cases where a native click is not dispatched following a valid keyboard interaction (due to the native semantics of the host element), it will be emulated by React Native for Web. This helps to improve the accessibility of elements for all forms of interaction hardware.

onClick ?(event: MouseEvent) => void

Called when the element is clicked.

onClickCapture ?(event: MouseEvent) => void

Called when the element is clicked. (Capture phase.)

onContextMenu ?(event: MouseEvent) => void

Called when a native context menu is displayed. This may be in response to mouse, touch, or mouse+keyboard interaction.


Focus Props API #

Focus interactions are available on supporting elements. The focus events are React DOM synthetic focus events. These events are also fired in response to focus being programmatically moved.

onBlur ?(event: FocusEvent) => void

Called when the element loses focus.

onFocus ?(event: FocusEvent) => void

Called when the element receives focus.


Keyboard Props API #

Keyboard interactions are available on supporting elements. The keyboard events are React DOM synthetic keyboard events.

onKeyDown ?(event: KeyboardEvent) => void

Called when a key is pressed down.

onKeyDownCapture ?(event: KeyboardEvent) => void

Called when a key is pressed down. (Capture phase.)

onKeyUp ?(event: KeyboardEvent) => void

Called when a key is released.

onKeyUpCapture ?(event: KeyboardEvent) => void

Called when a key is released. (Capture phase.)


Responder Props API #

“Responder” interactions are available on supporting elements. The Responder System allows views and gesture recognizers to opt-in to negotiating over a single, global “interaction lock”. For a view to become the “responder” means that pointer interactions are exclusive to that view and none other. A view can negotiate to become the “responder” without requiring knowledge of other views. A more specialized API for working with multi-pointer gestures is available by using the PanResponder module.

A view can become the “responder” after the following native events: scroll, touchstart, touchmove, mousedown, mousemove. If nothing is already the “responder”, the event propagates to (capture) and from (bubble) the event target until a view returns true for on*SetResponder(Capture). If a view is currently the responder, the negotiation event propagates to (capture) and from (bubble) the lowest common ancestor of the event target and the current responder. Then negotiation happens between the current responder and the view that wants to become the responder.

NOTE: For historical reasons (originating from React Native), mouse interactions are represented as a single touch.

Negotiation props #

A view can become the responder by using the negotiation callbacks. During the capture phase the deepest node is called last. During the bubble phase the deepest node is called first. The capture phase should be used when a view wants to prevent a descendant from becoming the responder. The first view to return true from any of the on*ShouldSetResponderCapture / on*ShouldSetResponder callbacks will either become the responder or enter into negotiation with the existing responder.

N.B. If stopPropagation is called on the event for any of the negotiation callbakcs, it only stops further negotiation within the Responder System. It will not stop the propagation of the native event (which has already bubbled to the document by this time.)

onStartShouldSetResponder ?(event: ResponderEvent) => boolean

On pointerdown, should this view attempt to become the responder? If the view is not the responder, this callback may be called for every pointer start on the view.

onStartShouldSetResponderCapture ?(event: ResponderEvent) => boolean

On pointerdown, should this view attempt to become the responder during the capture phase? If the view is not the responder, this callback may be called for every pointer start on the view.

onMoveShouldSetResponder ?(event: ResponderEvent) => boolean

On pointermove for an active pointer, should this view attempt to become the responder? If the view is not the responder, this callback may be called for every pointer move on the view.

onMoveShouldSetResponderCapture ?(event: ResponderEvent) => boolean

On pointermove for an active pointer, should this view attempt to become the responder during the capture phase? If the view is not the responder, this callback may be called for every pointer move on the view.

onScrollShouldSetResponder ?(event: ResponderEvent) => boolean

On scroll, should this view attempt to become the responder? If the view is not the responder, this callback may be called for every scroll of the view.

onScrollShouldSetResponderCapture ?(event: ResponderEvent) => boolean

On scroll, should this view attempt to become the responder during the capture phase? If the view is not the responder, this callback may be called for every scroll of the view.

onResponderTerminationRequest ?(event: ResponderEvent) => boolean

The view is the responder, but another view now wants to become the responder. Should this view release the responder? Returning true allows the responder to be released.

Transfer props #

If a view returns true for a negotiation callback then it will either become the responder (if none exists) or be involved in the responder transfer. The following callbacks are called only for the views involved in the responder transfer (i.e., no bubbling.)

onResponderGrant ?(event: ResponderEvent) => void

The view is granted the responder and is now responding to pointer events. The lifecycle callbacks will be called for this view. This is the point at which you should provide visual feedback for users that the interaction has begun.

onResponderReject ?(event: ResponderEvent) => void

The view was not granted the responder. It was rejected because another view is already the responder and will not release it.

onResponderTerminate ?(event: ResponderEvent) => void

The responder has been taken from this view. It may have been taken by another view after a call to onResponderTerminationRequest, or it might have been taken by the browser without asking (e.g., window blur, document scroll, context menu open). This is the point at which you should provide visual feedback for users that the interaction has been cancelled.

Lifecycle props #

If a view is the responder, the following callbacks will be called only for this view (i.e., no bubbling.) These callbacks are always bookended by onResponderGrant (before) and either onResponderRelease or onResponderTerminate (after).

onResponderStart ?(event: ResponderEvent) => void

A pointer down event occured on the screen. The responder is notified of all start events, even if the pointer target is not this view (i.e., additional pointers are being used). Therefore, this callback may be called multiple times while the view is the responder.

onResponderMove ?(event: ResponderEvent) => void

A pointer move event occured on the screen. The responder is notified of all move events, even if the pointer target is not this view (i.e., additional pointers are being used). Therefore, this callback may be called multiple times while the view is the responder.

onResponderEnd ?(event: ResponderEvent) => void

A pointer up event occured on the screen. The responder is notified of all end events, even if the pointer target is not this view (i.e., additional pointers are being used). Therefore, this callback may be called multiple times while the view is the responder.

onResponderRelease ?(event: ResponderEvent) => void

As soon as there are no more pointers that started inside descendants of the responder, this callback is called on the responder and the interaction lock is released. This is the point at which you should provide visual feedback for users that the interaction is over.

ResponderEvent #

Every callback is called with a ResponderEvent event. Data dervied from the native events, e.g., the native target and pointer coordinates, can be used to determine the return value of the negotiation callbacks, etc.

currentTarget EventTarget

The DOM element acting as the responder view.

defaultPrevented boolean
eventPhase number
isDefaultPrevented () => boolean
isPropagationStopped () => boolean
isTrusted boolean
nativeEvent TouchEvent
target EventTarget
timeStamp number
touchHistory TouchHistory

An object containing information about the history of touches.

TouchHistory

indexOfSingleActiveTouch number
mostRecentTimeStamp number
numberActiveTouches number
touchBank TouchBank

TouchBank

currentPageX number
currentPageY number
currentTimeStamp number
previousPageX number
previousPageY number
previousTimeStamp number
startPageX number
startPageY number
startTimeStamp number
touchActive number
Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/linking/index.html b/docs/docs/linking/index.html new file mode 100644 index 00000000..d94c9f92 --- /dev/null +++ b/docs/docs/linking/index.html @@ -0,0 +1,3 @@ +Linking // React Native for Web

Linking

Linking gives you a general interface for securely opening external URLs from JavaScript.

import { Linking } from 'react-native';

API #

Static methods #

canOpenURL (url) => Promise<boolean>

Returns a Promise that resolves to a boolean indicating whether the app can open the URL.

getInitialURL () => Promise<string>

Returns a Promise that resolves to the string of the URL that initially loaded the app.

openURL (url) => Promise<>

Try to open the given url in a secure fashion. The method returns a Promise object. If the url opens, the promise is resolved. If not, the promise is rejected.


Examples #

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/lists/index.html b/docs/docs/lists/index.html new file mode 100644 index 00000000..50332905 --- /dev/null +++ b/docs/docs/lists/index.html @@ -0,0 +1,3 @@ +Lists // React Native for Web

Lists

Basic support for FlatList, SectionList, and VirtualizedList.

These components are the same JavaScript implementations as those found in React Native. Please refer to the React Native documentation below:

Warning! The React Native list components are not optimized for the web. You may prefer to use external modules that are designed for multi-platform lists and provide better performance, e.g., RecyclerListView.


Examples #

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/localization/index.html b/docs/docs/localization/index.html new file mode 100644 index 00000000..a344fda8 --- /dev/null +++ b/docs/docs/localization/index.html @@ -0,0 +1,3 @@ +Localization // React Native for Web

Localization

Localized layout is largely automatic if you follow this guide.

React Native for Web provides several mechanisms to automatically flip application layout to match the writing direction of the primary language.

Localized component layout #

To automatically flip the layout of a flexbox or grid container, set the dir prop on View, Text, or TextInput components to desired writing direction (e.g., "rtl"). By default, the native writing direction is set to "auto" for Text and TextInput elements. This uses the browser’s built-in writing direction algorithm to detect whether the text should be displayed left-to-right or right-to-left.

You can also set the lang prop on Text or TextInput to provide browsers with information about the language of the text.

const style = { alignItems: 'flex-start' };
return (
<View dir="rtl" style={style}>
<Text lang="ar">...</Text>
</View>
);

The non-standard direction-independent style properties should also be used as much as possible. React Native for Web will automatically flip the direction of these properties when the application is re-rendered after using I18nManager to enable RTL mode.

// "start" is "left" for LTR and "right" for RTL
const style = { paddingStart: 10, marginStart: 10 };
return (
<View style={style} />
);

The I18nManager API can also be used to help with more fine-grained control of layout, e.g., flipping images or transforms.

const { isRTL } = I18nManager.getConstants();
const transform = { [{ scaleX: isRTL ? -1 : 1 }] };

<Image source={'forward.svg'} style={transform} />
<Image source={isRTL ? 'back.svg' : 'forward.svg'} />

Localized application layout #

The application will automatically display as RTL if rendered after setting the direction to RTL.

// Either force RTL (e.g., for unit tests)
I18nManager.forceRTL(true);

// Or set RTL if you know the language is RTL
I18nManager.setPreferredLanguageRTL(true);

Once the application is rendered in RTL mode, it will flip all the direction-independent styles and ensure that the isRTL constant is true.

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/modal/index.html b/docs/docs/modal/index.html new file mode 100644 index 00000000..88f53807 --- /dev/null +++ b/docs/docs/modal/index.html @@ -0,0 +1,3 @@ +Modal // React Native for Web

Modal

A basic way to present content above an enclosing view. Modals may be nested within other Modals.

import { Modal } from 'react-native';

<Modal {...props}>{children}</Modal>;

API #

Props #

animationType ?("fade" | "none" | "slide")

Default is "none". This can be used to add an animation to the modal being opened or closed.

children ?any

The children of a Modal element will be hidden or shown depending on the modal visibility.

onDismiss ?() => void

Called after the modal has been dismissed and is no longer visible.

onRequestClose ?() => void

Called when the user is attempting to close the modal like when they hit Escape. Only the top-most Modal responds to hitting Escape.

onShow ?() => void

Called after the modal has been shown and may be visible.

transparent ?boolean = false

Determines if the modal is rendered with a transparent backdrop or a white backdrop

visible ?boolean = true

Determines if the modal and its content is rendered.


Examples #

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/multi-platform/index.html b/docs/docs/multi-platform/index.html new file mode 100644 index 00000000..776ab71d --- /dev/null +++ b/docs/docs/multi-platform/index.html @@ -0,0 +1,3 @@ +Multi-platform setup // React Native for Web

Multi-platform setup

An overview of how to integrate React Native for Web into an existing React Native codebase.

If you are interested in making a multi-platform app it is strongly recommended that you use Expo (or learn from the source code for the Web integration). Expo includes web support and takes care of all the configuration work required.

If you have an existing application, this guide will surface the areas that require attention and customization before most web bundlers can consume the non-standard JavaScript in packages produced by the React Native ecosystem. Additionally, 3rd party React Native packages with web support are listed in the React Native Directory.


Package aliasing #

Bundler #

Configure your module bundler to alias the package to react-native. For example, modify your webpack configuration as follows:

// webpack.config.js
module.exports = {
// ...the rest of your config

resolve: {
alias: {
'react-native$': 'react-native-web'
}
}
}

Compiler #

Babel supports module aliasing using babel-plugin-module-resolver

{
"plugins": [
["module-resolver", {
"alias": {
"^react-native$": "react-native-web"
}
}]
]
}

Jest #

Jest can be configured using the provided preset. This will map react-native to react-native-web and provide appropriate mocks. Please refer to the Jest documentation for more information.

{
"preset": "react-native-web"
}

Flow #

Flow can be configured to understand the aliased module. You may also need to include a custom libdef (example) in your config.

[options]
module.name_mapper='^react-native$' -> 'react-native-web'

Node.js #

Node.js can alias react-native to react-native-web using module-alias. This is useful if you want to pre-render the app (e.g., server-side rendering or build-time rendering).

// Install the `module-alias` package as a dependency first
const moduleAlias = require("module-alias");
moduleAlias.addAliases({
"react-native": require.resolve("react-native-web"),
});
moduleAlias();

Root element #

Full-screen React Native apps may require the following styles inlined in the HTML document shell. (Example.)

/* These styles make the body full-height */
html, body { height: 100%; }
/* These styles disable body scrolling if you are using <ScrollView> */
body { overflow: hidden; }
/* These styles make the root element full-height */
#root { display:flex; height:100%; }

Web-specific code #

Minor platform differences can use the Platform module.

import { Platform } from 'react-native';

const styles = StyleSheet.create({
height: (Platform.OS === 'web') ? 200 : 100,
});

More significant platform differences should use platform-specific files (see the webpack configuration below for resolving *.web.js files):

For example, with the following files in your project:

MyComponent.android.js
MyComponent.ios.js
MyComponent.web.js

And the following import:

import MyComponent from './MyComponent';

React Native will automatically import the correct variant for each specific target platform.


Compiling and Bundling #

What follows is only an example of a basic way to package a Web app using webpack and Babel. (Metro is the React Native bundler with undocumented web support.)

Install webpack-related dependencies, for example:

npm install --save-dev babel-loader url-loader webpack webpack-cli webpack-dev-server

React Native’s Babel preset rewrites ES modules to CommonJS modules, preventing bundlers from automatically performing “tree-shaking” to remove unused modules from your web app build. To help with this, you can install the following Babel plugin:

npm install --save-dev babel-plugin-react-native-web

Create a web/webpack.config.js file:

// web/webpack.config.js

const path = require('path');
const webpack = require('webpack');

const appDirectory = path.resolve(__dirname, '../');

// This is needed for webpack to compile JavaScript.
// Many OSS React Native packages are not compiled to ES5 before being
// published. If you depend on uncompiled packages they may cause webpack build
// errors. To fix this webpack can be configured to compile to the necessary
// `node_module`.
const babelLoaderConfiguration = {
test: /\.js$/,
// Add every directory that needs to be compiled by Babel during the build.
include: [
path.resolve(appDirectory, 'index.web.js'),
path.resolve(appDirectory, 'src'),
path.resolve(appDirectory, 'node_modules/react-native-uncompiled')
],
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
// The 'metro-react-native-babel-preset' preset is recommended to match React Native's packager
presets: ['module:metro-react-native-babel-preset'],
// Re-write paths to import only the modules needed by the app
plugins: ['react-native-web']
}
}
};

// This is needed for webpack to import static images in JavaScript files.
const imageLoaderConfiguration = {
test: /\.(gif|jpe?g|png|svg)$/,
use: {
loader: 'url-loader',
options: {
name: '[name].[ext]'
}
}
};

module.exports = {
entry: [
// load any web API polyfills
// path.resolve(appDirectory, 'polyfills-web.js'),
// your web-specific entry file
path.resolve(appDirectory, 'index.web.js')
],

// configures where the build ends up
output: {
filename: 'bundle.web.js',
path: path.resolve(appDirectory, 'dist')
},

// ...the rest of your config

module: {
rules: [
babelLoaderConfiguration,
imageLoaderConfiguration
]
},

resolve: {
// This will only alias the exact import "react-native"
alias: {
'react-native$': 'react-native-web'
},
// If you're working on a multi-platform React Native app, web-specific
// module implementations should be written in files using the extension
// `.web.js`.
extensions: [ '.web.js', '.js' ]
}
}

To run in development from the root of your application:

./node_modules/.bin/webpack-dev-server -d --config ./web/webpack.config.js --inline --hot --colors

To build for production:

./node_modules/.bin/webpack -p --config ./web/webpack.config.js

Please refer to the Webpack documentation for more information on configuration.

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/pan-responder/index.html b/docs/docs/pan-responder/index.html new file mode 100644 index 00000000..00e0a551 --- /dev/null +++ b/docs/docs/pan-responder/index.html @@ -0,0 +1,3 @@ +PanResponder // React Native for Web

PanResponder

PanResponder reconciles several pointers into a single gesture. It makes single-pointer gestures resilient to extra touches, and can be used to recognize basic multi-touch gestures.

Please refer to the React Native documentation below:


Examples #

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/picker/index.html b/docs/docs/picker/index.html new file mode 100644 index 00000000..bc571c08 --- /dev/null +++ b/docs/docs/picker/index.html @@ -0,0 +1,3 @@ +Picker // React Native for Web

Picker

Renders the native <select> component

import { Picker } from 'react-native';

<Picker {...props}>
<Picker.Item />
</Picker>;

API #

Props #

...ViewProps ?ViewProps

All the props supported by View.

children ?(...Picker.Item)

The items to display in the picker must be of type Picker.Item.

enabled ?boolean = true

Determines if the picker will be disabled, i.e., the user will not be able to make a selection.

onValueChange ?(value, index) => void

Callback for when an item is selected. This is called with the value and index prop of the item that was selected.

selectedValue ?string

Select the item with the matching value.

style ?{ ...ViewProps.style, color: ?string }

Supported style properties.

Picker.Item #

color ?string

Color of the item label. (Limited by browser support.)

label ?string

Text to display for this item.

testID ?string

Used to locate this view in end-to-end tests.

value ?(number | string)

The value to be passed to the picker’s onValueChange callback when this item is selected.

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/pixel-ratio/index.html b/docs/docs/pixel-ratio/index.html new file mode 100644 index 00000000..e9df42d7 --- /dev/null +++ b/docs/docs/pixel-ratio/index.html @@ -0,0 +1,3 @@ +PixelRatio // React Native for Web

PixelRatio

PixelRatio class gives access to the device pixel density.

import { PixelRatio } from 'react-native';

API #

Static methods #

get () => number

Returns the device pixel density as a number.

getFontScale () => number

On web this returns the device pixel ratio as a number.

getPixelSizeForLayoutSize (number) => number

Converts a layout size (dp) to pixel size (px). Guaranteed to return an integer number.

roundToNearestPixel (number) => number

Rounds a layout size (dp) to the nearest layout size that corresponds to an integer number of pixels. For example, on a device with a PixelRatio of 3, PixelRatio.roundToNearestPixel(8.4) = 8.33, which corresponds to exactly (8.33 * 3) = 25 pixels.

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/platform/index.html b/docs/docs/platform/index.html new file mode 100644 index 00000000..c238fd76 --- /dev/null +++ b/docs/docs/platform/index.html @@ -0,0 +1,3 @@ +Platform // React Native for Web

Platform

Detect what is the platform in which the app is running.

This piece of functionality can be useful when only small parts of a component are platform specific.

import { Platform } from 'react-native';

API #

Static properties #

OS "web"

This value will be "web" when running in a Web browser.

Static methods #

select (config) => any

Takes an object containing Platform.OS values as keys and returns the value for the platform you are currently running on.

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/pressable/index.html b/docs/docs/pressable/index.html new file mode 100644 index 00000000..be6438a9 --- /dev/null +++ b/docs/docs/pressable/index.html @@ -0,0 +1,3 @@ +Pressable // React Native for Web

Pressable

Pressable is a component that can detect various parts of press interactions on any of its defined children.

Pressable responds to touch, mouse, and keyboard interactions. The interaction state of the view is exposed to the children and style props which accept a callback as their value. The hover state is only activated by mouse interactions.

import { Pressable } from 'react-native';

<Pressable {...props}>{children}</Pressable>;

API #

Props #

...ViewProps ?ViewProps

All the props supported by View.

children ?(any | (state: InteractionState) => any)

The children of the view. Supports computing children as a function of interaction state.

delayLongPress ?number = 500

How long to delay calling onLongPress after onPressIn is called.

delayPressIn ?number = 0

How long to delay calling onPressIn after an interaction begins.

delayPressOut ?number = 0

How long to delay calling onPressOut after an interaction ends.

disabled ?boolean

Disables all pointer interactions with the element.

onHoverIn ?(e: MouseEvent) => void

Called when the pointer starts hovering over the element. Touch interactions have no effect.

onHoverOut ?(e: MouseEvent) => void

Called when the pointer stops hovering over the element. Touch interactions have no effect.

onLongPress ?() => void

Called when the pointer is held down for as long as the value of delayLongPress.

onPress ?(e: MouseEvent) => void

Called when the pointer is released without first being cancelled (e.g. by a scroll that steals the responder lock). Equivalent to the click DOM event.

onPressIn ?(e: ResponderEvent) => void

Called when the pointer starts interacting with the element after delayPressIn ms.

onPressOut ?(e: ResponderEvent) => void

Called when the pointer stops interacting with the element after delayPressOut ms.

style ?(Style | (state: InteractionState) => Style)

The style of the view. Supports computing style as a function of interaction state.

testOnly_hovered ?boolean

Used only for documentation or testing (e.g. snapshot testing).

testOnly_pressed ?boolean

Used only for documentation or testing (e.g. snapshot testing).

InteractionState #

The state object passed to function values of children and state reflects the current state of the user interaction with the view.

focused boolean

Whether the view is currently focused.

hovered boolean

Whether the view is being hovered over by a mouse.

pressed boolean

Whether the view is being pressed by a pointer or keyboard interaction key.


Examples #

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/progress-bar/index.html b/docs/docs/progress-bar/index.html new file mode 100644 index 00000000..164ffa69 --- /dev/null +++ b/docs/docs/progress-bar/index.html @@ -0,0 +1,3 @@ +ProgressBar // React Native for Web

ProgressBar

Display an activity progress bar.

import { ProgressBar } from 'react-native';

<ProgressBar {...props} />;

API #

Props #

...ViewProps ?ViewProps

All the props supported by View.

color ?string = "#1976D2"

Set the background color of the button.

indeterminate ?boolean = false

Whether the progress bar will show indeterminate progress.

progress ?number = 0

The progress value between 0 and 1.

trackColor ?string = "transparent"

Customize the color of the track bar.


Examples #

Custom sizes can be created using style properties.

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/react-native-compatibility/index.html b/docs/docs/react-native-compatibility/index.html new file mode 100644 index 00000000..4611b85f --- /dev/null +++ b/docs/docs/react-native-compatibility/index.html @@ -0,0 +1,3 @@ +React Native compatibility // React Native for Web

React Native compatibility

React Native for Web provides compatibility with the vast majority of React Native’s JavaScript API. Features deprecated in React Native should be considered unsupported in React Native for Web.

Best used with React Native >= 0.63.

Visit the React Native Directory to find React Native packages with known web support.

Components #

NameStatusNotes
ActivityIndicator
Button
CheckBox
FlatList
ImageMissing multiple sources (#515) and HTTP headers (#1019).
ImageBackground
KeyboardAvoidingView(✓)Mock. No equivalent web APIs.
Modal
Picker
Pressable
RefreshControlNot started (#1027).
SafeAreaView
ScrollViewMissing momentum scroll events (#1021).
SectionList
StatusBar(✓)Mock. No equivalent web APIs.
Switch
TextMissing onLongPress (#1011) support.
TextInputMissing rich text features (#1023), and auto-expanding behaviour (#795).
TouchableIncludes additional support for mouse and keyboard interactions.
TouchableHighlight
TouchableNativeFeedbackNot started (#1024).
TouchableOpacity
TouchableWithoutFeedback
View
VirtualizedList
YellowBox(✓)Mock. No YellowBox functionality.

APIs #

NameStatusNotes
AccessibilityInfo(✓)Mock. No equivalent web APIs.
AlertNot started (#1026).
AnimatedMissing useNativeDriver support.
Appearance
AppRegistryIncludes additional support for server rendering with getApplication.
AppState
BackHandler(✓)Mock. No equivalent web APIs.
Clipboard
DeviceInfo(✓)Limited information.
Dimensions
Easing
Geolocation
I18nManagerIncludes additional support for runtime switch to RTL.
InteractionManager(✓)
Keyboard(✓)Mock.
LayoutAnimation(✓)Missing translation to web animations.
Linking
NativeEventEmitter
NativeMethodsMixin
NativeModules(✓)Mocked. Missing ability to load native modules.
PanResponder
PixelRatio
Platform
SettingsNo equivalent web APIs.
ShareOnly available over HTTPS. Read about the Web Share API.
StyleSheet
UIManager
Vibration
useColorScheme
useWindowDimensions
Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/rendering/index.html b/docs/docs/rendering/index.html new file mode 100644 index 00000000..31c28cd5 --- /dev/null +++ b/docs/docs/rendering/index.html @@ -0,0 +1,3 @@ +Rendering // React Native for Web

Rendering

Client and server rendering with React Native for Web.

React Native for Web can be used for multi-platform and web-only applications. It can incrementally adopted by existing React Web apps and integrated with existing React Native apps. Preact is also supported.

React Native for Web components interoperate with React DOM components. They can be incrementally introduced at any point in an application’s component tree. One thing to be aware of is that external CSS applied to all tags in a document may interfere with the default rendering of some React Native for Web components.


Client API #

Render apps using AppRegistry:

// index.web.js

import { AppRegistry } from 'react-native';
import App from './src/App';

// register the app
AppRegistry.registerComponent('App', () => App);

AppRegistry.runApplication('App', {
initialProps: {},
rootTag: document.getElementById('root')
});

Or render individual components:

import { render } from 'react-native';
import Header from './src/Header';

render(<Header />, document.getElementById('header'))

You might need to adjust the styles of the HTML document’s root elements for your app to fill the viewport.

<html style="height:100%">
<body style="height:100%">
<div id="root" style="display:flex;height:100%"></div>

Warning! Although components in can be rendered by calling ReactDOM.render directly, this will not set the global context React Native provides to components when using the AppRegistry API.


Server API #

Server-side rendering to HTML is supported using AppRegistry:

import App from './src/App';
import ReactDOMServer from 'react-dom/server';
import { AppRegistry } from 'react-native-web';

// register the app
AppRegistry.registerComponent('App', () => App);

// prerender the app
const { element, getStyleElement } = AppRegistry.getApplication('App', { initialProps });
// first the element
const html = ReactDOMServer.renderToString(element);
// then the styles (optionally include a nonce if your CSP policy requires it)
const css = ReactDOMServer.renderToStaticMarkup(getStyleElement({ nonce }));

// example HTML document string
const document = `
<!DOCTYPE html>
<html style="height:100%">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
${css}
<body style="height:100%; overflow-y:hidden">
<div id="root" style="display:flex; height: 100%">
${html}
</div>
<script nonce="
${nonce}" src="${bundlePath}"></script>
`
Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/scroll-view/index.html b/docs/docs/scroll-view/index.html new file mode 100644 index 00000000..2f6c22a1 --- /dev/null +++ b/docs/docs/scroll-view/index.html @@ -0,0 +1,3 @@ +ScrollView // React Native for Web

ScrollView

A scrollable view that provides integration with the pointer-locking responder system.

ScrollView must have a bounded height: either set the height of the view directly (discouraged) or make sure all parent views have bounded height (e.g., apply { flex: 1} down the view stack).

import { ScrollView } from 'react-native';

<ScrollView {...props}>{children}</ScrollView>;

API #

Props #

...ViewProps ?ViewProps

All the props supported by View.

contentContainerStyle ?Style

These styles will be applied to the scroll view content container which wraps all of the child views.

disableScrollViewPanResponder ?boolean = false

When true, the default PanResponder on the ScrollView is disabled, and full control over pointers inside the ScrollView is left to its child components. This is meant to be used when native “snap-to” scrolling behavior is needed.

horizontal ?boolean = false

When true, the scroll view’s children are arranged horizontally in a row instead of vertically in a column.

keyboardDismissMode ?("none" | "on-drag")

Determines whether the keyboard gets dismissed in response to a scroll drag.

onContentSizeChange ?(width: number, height: number) => void

Called when scrollable content view of the ScrollView changes.

onScroll ?(e: ScrollEvent) => void

Called during scrolling. The frequency of the events can be controlled using the scrollEventThrottle prop.

pagingEnabled ?boolean = false

When true, the scroll view snaps to individual items in the list when scrolling.

scrollEnabled ?boolean = true

When false, the content does not scroll.

scrollEventThrottle ?number = 0

This controls how often the scroll event will be fired while scrolling (as a time interval in ms). A lower number yields better accuracy for code that is tracking the scroll position, but can lead to scroll performance problems. The default value is 0, which means the scroll event will be sent only once each time the view is scrolled.

stickyHeaderIndices ?Array<number>

An array of child indices determining which children get docked to the top of the screen when scrolling. For example, passing stickyHeaderIndices={0} will cause the first child to be fixed to the top of the scroll view. This property is not supported in conjunction with the horizontal prop.

ScrollEvent #

The nativeEvent on the event passed to onScroll is a custom object of information related to the layout of the ScrollView.

contentOffset { x: number, y: number}

How far the scroll view is scrolled along each axis.

contentSize { height: number, width: number}

The size of the scrollable content area.

layoutMeasurement { height: number, width: number}

The border-box height and width of the scroll view.

Instant methods #

getInnerViewNode () => void

Returns a reference to the underlying content container DOM node within the ScrollView.

getScrollableNode () => void

Returns a reference to the underlying scrollable DOM node.

getScrollResponder () => void

Returns a reference to the underlying scroll responder, which supports operations like scrollTo(). All ScrollView-like components should implement this method so that they can be composed while providing access to the underlying scroll responder’s methods.

scrollTo (options?: { x: number, y: number, animated: boolean }) => void

Scrolls to a given x, y offset (animation depends on browser support for scroll-behavior).

scrollToEnd (options?: { animated: boolean }) => void

Scrolls to the end of the scroll view.


Examples #

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/style-sheet/index.html b/docs/docs/style-sheet/index.html new file mode 100644 index 00000000..1fc81621 --- /dev/null +++ b/docs/docs/style-sheet/index.html @@ -0,0 +1,3 @@ +StyleSheet // React Native for Web

StyleSheet

Work with strict styles that provide deterministic rendering and automatically adapt to localized writing direction.

The StyleSheet abstraction converts predefined styles to (vendor-prefixed) CSS without requiring a compile-time step. Styles that cannot be resolved outside of the render loop (e.g., dynamic positioning) are usually applied as inline styles.

import { StyleSheet } from 'react-native';

Did you know? StyleSheet automatically merges styles and produces “utility” CSS for lightweight, reliable, and performant styling. Read more in the styling guide.


API #

Static properties #

absoluteFill ?number

A very common pattern is to create overlays with position absolute and zero positioning, so absoluteFill can be used for convenience and to reduce duplication of these repeated styles.

absoluteFillObject ?Object

Sometimes you may want absoluteFill but with a couple tweaks - absoluteFillObject can be used to create a customized entry in a StyleSheet.

hairlineWidth ?Object

Equal to 1px. This is not implemented using screen density as browsers may round sub-pixel values down to 0, causing the line not to be rendered.

Static methods #

compose (style1, style2) => Style

Combines two styles such that the last style overrides properties of the first style. If either style is falsy, the other one is returned without allocating an array, saving allocations and maintaining reference equality.

create ({ [key]: ruleset }) => ({ [key]: number })

Define style objects. Each key of the object passed to create must define a style object. These values are opaque and should not be introspected.

flatten (styles: Style) => Object

Lookup a style object by ID or flatten an array of styles into a single style object.

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/styling/index.html b/docs/docs/styling/index.html new file mode 100644 index 00000000..6b40f428 --- /dev/null +++ b/docs/docs/styling/index.html @@ -0,0 +1,3 @@ +Styling // React Native for Web

Styling

React Native for Web relies on authoring styles in JavaScript and produces optimized CSS.

Style declarations are authored in JavaScript and applied to elements using the style prop. React Native for Web includes a very small CSS reset that only removes unwanted User Agent styles beyond the reach of React components. All other styles are scoped to components and implemented as “utility” CSS that deduplicates styles and provides reliable rendering.

const style = { flex: 1, opacity: 0 };
const Component = () => <View style={style} />;

Style performance is improved when styles are defined outside of components using the StyleSheet API. This creates opaque references to the styles that cannot be directly accessed unless first passed to StyleSheet.flatten.

const styles = StyleSheet.create({ root: { flex: 1, opacity: 0 } });
const Component = () => <View style={styles.root} />;

All the React Native components accept a style property. The value can be a registered object, a plain object, or an array of objects. The array syntax will merge styles from left-to-right as normal JavaScript objects, and can be used to conditionally apply styles:

<View style={[ styles.element, isActive && styles.active ]} />

To let other components customize the style of a component’s children you can expose a prop so styles can be explicitly passed into the component.

function List(props) {
return (
<View style={props.style}>
{elements.map((element) =>
<View style={[ styles.element, props.elementStyle ]} />
)}
</View>
);
}

function App() {
return (
<List
elementStyle={styles.listElement}
style={styles.list}
/>

);
}

You have greater control over how styles are composed when compared to using class names. For example, you may choose to accept a limited subset of style props in the component’s API, and control the order and conditions of their merging.


Styles API #

React Native for Web supports all long-form CSS properties. There is no direct support for @-rules, selectors, pseudo-selectors, and pseudo-elements, equivalents of which are demonstrated in the styling patterns section below.

Short-form properties #

The only supported short-form CSS properties accept only a single value.

borderColor ?string

Accepts only a single value that is applied to all sides.

borderRadius ?(number | string)

Accepts only a single value that is applied to all sides.

borderStyle ?string

Accepts only a single value that is applied to all sides.

borderWidth ?(number | string)

Accepts only a single value that is applied to all sides.

flex ?number

Accepts only positive integers, 0, or -1.
The value of -1 is non-standard and equivalent to setting flowGrow:0 and flexShrink:1.

margin ?(number | string)

Accepts only a single value that is applied to all sides.

overflow ?("auto" | "hidden" | "visible")

Accepts only a single value that is applied to both axes.

overscrollBehavior ?("auto" | "contain" | "none")

Accepts only a single value that is applied to both axes.

padding ?(number | string)

Accepts only a single value that is applied to all sides.

Non-standard properties #

React Native for Web includes compatibility with the following non-standard React Native properties and values.

animationKeyframes ?Object

A web-only CSS extension for defining keyframes. The value is an object representing a CSS keyframes definition. For example: { '0%': { opacity: 1 } }.

borderEndColor ?string

Equivalent to border-inline-end-color.

borderEndStyle ?string

Equivalent to border-inline-end-style.

borderEndWidth ?(string | number)

Equivalent to border-inline-end-width.

borderStartColor ?string

Equivalent to border-inline-start-color.

borderStartStyle ?string

Equivalent to border-inline-start-style.

borderStartWidth ?(string | number)

Equivalent to border-inline-start-width.

borderBottomEndRadius ?(string | number)

Equivalent to border-end-end-radius.

borderBottomStartRadius ?(string | number)

Equivalent to border-end-start-radius.

borderTopEndRadius ?(string | number)

Equivalent to border-start-end-radius.

borderTopStartRadius ?(string | number)

Equivalent to border-start-start-radius.

end ?(string | number)

Defines the logical inline end position of an element. Equivalent to right for ltr writing direction.

marginHorizontal ?(number | string)

Equivalent to margin-inline. Accepts only a single value.

marginVertical ?(number | string)

Equivalent to margin-block.

marginEnd ?(string | number)

Equivalent to margin-inline-end.

marginStart ?(string | number)

Equivalent to margin-inline-start.

paddingHorizontal ?(number | string)

Equivalent to padding-inline. Accepts only a single value.

paddingVertical ?(number | string)

Equivalent to padding-block. Accepts only a single value.

paddingEnd ?(string | number)

Equivalent to padding-inline-end.

paddingStart ?(string | number)

Equivalent to padding-inline-start.

shadowColor ?string
shadowOffset ?(string | number)
shadowOpacity ?number
shadowRadius ?(string | number)
start ?(string | number)

Defines the logical inline end position of an element. Equivalent to left for ltr writing direction.

textAlign ?string

Includes support for non-standard "start" and "end" values for localization support.

textAlignVertical ?string

Equivalent to vertical-align.

textShadowColor ?string
textShadowOffset ?(string | number)
textShadowRadius ?(string | number)
transform ?Array<Object>

Implements React Native’s JavaScript syntax for transforms.

writingDirection ?("auto" | "ltr" | "rtl")

Equivalent to direction.


Text style inheritance #

Web developers will be used to setting “global” font styles that are applied to the entire document, taking advantage of inherited CSS properties.

html {
font-family: Arial, sans-serif;
font-size: 16px;
color: #333;
}

However, this approach is problematic for component-based systems, as the rendering of a component may be affected by text styles unexpectedly inherited from its ancestors. React Native for Web adopts the same inheritance restrictions found in React Native: all text nodes must be contained by a Text component and cannot be rendered directly within a View; and text style inheritance is only available within Text subtrees.

// BAD
<View>Some text</View>
// GOOD
<View><Text>Some text</Text></View>

The consequence of this is that default text styles cannot be set on View for an entire subtree. Although this may seem limiting, it ensures that different design systems can co-exist on the same page and text styles are always encapsulated. The recommended way to use consistent text styles across your application is to create a custom text component (e.g., AppText) that implements those styles and forms the basis of further app-specific text customization.

<View>
<AppHeaderText>App header text</AppHeaderText>
<AppText>App default text</AppText>
</View>

This still allows for text style inheritance within the Text subtree.

const bold = { fontWeight: 'bold' }
const red = { color: 'red' }

<Text style={bold}>
I am bold
<Text style={red}>and red</Text>
</Text>

This approach means that components are designed with isolation in mind. You should be able to drop a component anywhere in your application, trusting that as long as the props are the same, it will look and behave the same way. Text properties that could inherit from outside of the props would break this isolation.


Styling patterns #

The styling system in React Native is a way of defining the styles your application requires; it does not concern itself with where or when those styles are applied to elements. As a result, there is no dedicted Media Query or pseudo-class API built into the styling system. Instead, the state of the application should be derived from the equivalent JavaScript APIs that have the benefit of not being limited to modifying only styles.

Responsive layouts #

Media Queries may not be most appropriate for component-based designs, as adapting to the dimensions of a container is often preferred. This can be done with the onLayout prop found on all the core components. If you do choose to use Media Queries, using them in JavaScript via the matchMedia DOM API has the benefit of allowing you to swap out entire components, not just styles.

Interaction states #

Interactions such as hover, focus, and press should be implemented using events (e.g., onFocus). Components like Pressable expose interaction state in a ready-to-use form.

Debugging #

React Dev Tools supports inspecting and editing of React Native styles. It’s recommended that you rely more on React Dev Tools and live/hot-reloading rather than inspecting and editing the DOM directly.


How it works #

Style resolution is deterministic and slightly different from CSS. In the following HTML/CSS example, the .margin selector is defined last in the CSS and takes precedence over the previous rules, resulting in a margin of 0,0,0,0.

<style>
.marginTop { margin-top: 10px; }
.marginBottom { margin-bottom: 20px; }
.margin { margin: 0; }
</style>

<div class="marginTop marginBottom margin"></div>

But in React Native for Web the most precise style property takes precedence, resulting in margins of 10,0,20,0.

const style = [
{ marginTop: 10 },
{ marginBottom: 20 },
{ margin: 0 }
];

const Box = () => <View style={style} />

React Native for Web transforms styles objects into CSS and inline styles. Any styles defined using StyleSheet.create will ultimately be rendered using CSS class names. Each rule is broken down into declarations, properties are expanded to their long-form, and the resulting key-value pairs are mapped to unique “atomic CSS” class names.

Input:

const Box = () => <View style={styles.box} />

const styles = StyleSheet.create({
box: {
margin: 0
}
});

Output:

<style>
.rn-1mnahxq { margin-top: 0px; }
.rn-61z16t { margin-right: 0px; }
.rn-p1pxzi { margin-bottom: 0px; }
.rn-11wrixw { margin-left: 0px; }
</style>

<div class="r-156q2ks r-61z16t r-p1pxzi r-11wrixw"></div>

This ensures that CSS order doesn’t impact rendering and CSS rules are efficiently deduplicated. Rather than the total CSS growing in proportion to the number of rules, it grows in proportion to the number of unique declarations. As a result, the DOM style sheet is only written to when new unique declarations are defined and it is usually small enough to be pre-rendered and inlined.

Class names are deterministic, which means that the resulting CSS and HTML is consistent across builds – important for large apps using code-splitting and deploying incremental updates.

At runtime registered styles are resolved to DOM style props and memoized. Any dynamic styles that contain declarations previously registered as static styles can also be converted to CSS class names. Otherwise, they render as inline styles.

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/switch/index.html b/docs/docs/switch/index.html new file mode 100644 index 00000000..bcc96b4e --- /dev/null +++ b/docs/docs/switch/index.html @@ -0,0 +1,3 @@ +Switch // React Native for Web

Switch

A controlled component that renders a boolean input.

Switch requires an onValueChange callback that updates the value prop in order for the component to reflect user actions. If the value prop is not updated, the component will continue to render the supplied value prop instead of the expected result of any user actions.

import { Switch } from 'react-native';

<Switch {...props} />;

API #

Props #

...ViewProps ?ViewProps

All the props supported by View.

activeThumbColor ?string = "#009688"

The color of the thumb grip when the switch is turned on. (Web-only)

activeTrackColor ?string = "#A3D3CF"

The color of the track when the switch is turned on. (Web-only)

disabled ?boolean

Disables interactions with the element. If true, the user won’t be able to interact with the switch.

onValueChange ?(boolean) => void

Invoked with the new value when the value changes.

thumbColor ?string = "#FAFAFA"

The color of the thumb grip when the switch is turned off.

trackColor ?string => "#939393"

The color of the track when the switch is turned off.

value ?boolean = false

The value of the switch. If true the switch will be turned on.


Examples #

Custom sizes can be created using styles.

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/text-input/index.html b/docs/docs/text-input/index.html new file mode 100644 index 00000000..4e9ae1df --- /dev/null +++ b/docs/docs/text-input/index.html @@ -0,0 +1,3 @@ +TextInput // React Native for Web

TextInput

Accessible single- and multi-line text input via a keyboard.

Supports features such as auto-complete, auto-focus, placeholder text, and event callbacks. Note: some props are exclusive to or excluded from multiline.

import { TextInput } from 'react-native-web';

<TextInput {...props} />;

API #

Props #

...AccessibilityProps

The accessibility props.

...ClickProps

The click props.

...FocusProps

The focus props.

autoCapitalize ?string

Equivalent to HTMLElement.autocapitalize.

autoComplete ?string

Equivalent to HTMLElement.autocomplete.

autoCorrect ?("on" | "off")

A string indicating whether or not auto-correct behavior is on or off. Safari only.

autoFocus ?boolean = false

If true, focuses the input on mount. Only the first form element in a document with auto-focus is focused.

blurOnSubmit ?boolean

If true, the text field will blur when submitted. The default value is true for single-line fields and false for multiline fields. Note, for multiline fields setting blurOnSubmit to true means that pressing return will blur the field and trigger the onSubmitEditing event instead of inserting a newline into the field.

clearTextOnFocus ?boolean = false

If true, clears the text field automatically when focused.

dataSet ?Object

Equivalent to HTMLElement.dataset.

defaultValue ?string

The initial value of the input. Useful for simple use-cases where you don’t want to deal with listening to events and updating the value prop to keep the controlled state in sync.

direction ?("auto" | "ltr" | "rtl") = "auto"

Equivalent to HTMLElement.dir

disabled ?boolean = false

Equivalent to HTMLElement.disabled

editable ?boolean = true

Equivalent to HTMLElement.readonly

keyboardType ?string

Hints at the type of data that might be entered by the user while editing the element or its contents. Equivalent to HTMLElement.inputMode. Safari iOS requires an ancestral

element to display the search keyboard. (Not available when multiline is true.)

lang ?string

Equivalent to HTMLElement.lang.

maxLength ?string

Equivalent to HTMLElement.maxlength.

multiline ?boolean = false

If true, the text input can be multiple lines.

nativeID ?string

Equivalent to HTMLElement.id.

numberOfLines ?number = 1

Sets the number of lines for a multiline input. (Requires multiline to be true.)

onChange ?(e: ChangeEvent) => void

Equivalent to the React DOM ChangeEvent.

onChangeText ?(text: string) => void

Called when the text content of the input changes.

onContentSizeChange ?({ nativeEvent: { contentSize: { width, height } } }) => void

Callback that is called when the text input’s content size changes.

onKeyPress ?(e: KeyboardEvent) => void

Equivalent to the onKeyDown prop.

onLayout ?({ nativeEvent: { layout: { x, y, width, height } } }) => void

This is invoked when a component is mounted and when its layout changes. x and y are the offsets from the parent node.

onScroll ?(e: ScrollEvent) => void

Called during scrolling.

onSelectionChange ?({ nativeEvent: { selection: { start, end } } }) => void

Callback that is called when the text input’s selection changes.

onSubmitEditing ?() => void

Callback that is called when the keyboard’s submit button is pressed. When multiline={true}, this is only called if blurOnSubmit={true}.

placeholder ?boolean

Text that appears in the form control when it has no value set.

placeholderTextColor ?string

Equivalent to defining ::placeholder { color } via a CSS property.

required ?boolean

Equivalent to HTMLElement.required

returnKeyType ?string

Specifies what action label (or icon) to present for the enter key on virtual keyboards. Equivalent to HTMLElement.enterkeyhint

secureTextEntry ?boolean = false

Set to true for passwords and other sensitive data. Equivalent to HTMLInputElement “password” type. (Not available when multiline is true.)

selectTextOnFocus ?boolean = false

If true, all text will automatically be selected on focus.

spellCheck ?boolean

Equivalent to HTMLElement.spellcheck

style ?Style

Set the styles of the view. TextInput supports typographic styles in addition to those of View.

testID ?string

Set the test selector label (via data-testid).

value ?string

The value of the input when using it as a controlled component.

Instance methods #

blur () => void

Blur the underlying DOM input.

clear () => void

Clear the text from the underlying DOM input.

focus () => void

Focus the underlying DOM input.

isFocused () => boolean

Returns true if the input is currently focused; false otherwise.


Examples #

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/text/index.html b/docs/docs/text/index.html new file mode 100644 index 00000000..e89ae203 --- /dev/null +++ b/docs/docs/text/index.html @@ -0,0 +1,3 @@ +Text // React Native for Web

Text

The fundamental text primitive. Text inherits typographic styles from ancestor Text elements.

Text has built in accessibility controls, enforces inline layout by default, provides limited inheritance of text styles, and supports View as children. It inherits typographic styles from ancestor Text elements (as long as the chain of text elements is not interrupted by a View). By default, text is rendered using the native platform’s algorithm to determine the directionality of the content language.

import { Text } from 'react-native';

<Text {...props}>{children}</Text>;

Did you know? Text styling in React Native for Web has stricter rules than it does on the web. Read the Styling guide to learn more.


API #

Props #

...AccessibilityProps

The accessibility props.

...ClickProps

The click props.

...FocusProps

The focus props.

...KeyboardProps

The keyboard props.

...ResponderProps

The responder props.

children any

The children of a Text element can be strings as well as other elements like <View /> and <Image />. Nested text components will inherit the typographic styles of their parents.

dataSet ?Object

Equivalent to HTMLElement.dataset.

dir ?("auto" | "ltr" | "rtl") = "auto"

Equivalent to HTMLElement.dir. The default value of "auto" is not set on nested text elements.

focusable ?boolean

Set whether the view can receive keyboard focus.

href ?string

If href is defined, the view is rendered as an anchor tag pointing to this URL.

hrefAttrs ?Object

If href is defined, this prop defines related attributes to include on the anchor (e.g., download, rel, target) which may modify its behavior.

lang ?string

Equivalent to HTMLElement.lang.

nativeID ?string

Equivalent to HTMLElement.id.

numberOfLines ?number

Truncates the text with an ellipsis after this many lines.

onLayout ?({ nativeEvent: { layout: { x, y, width, height } } }) => void

This is invoked when a component is mounted and when its layout changes. x and y are the offsets from the parent node.

selectable ?boolean = true

When false, the text is not selectable.

style ?Style

Set the styles of the text. Text supports typographic styles in addition to those of View.

testID ?string

Set the test selector label (via data-testid).


Examples #

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/touchables/index.html b/docs/docs/touchables/index.html new file mode 100644 index 00000000..e43e0ae3 --- /dev/null +++ b/docs/docs/touchables/index.html @@ -0,0 +1,3 @@ +Touchables // React Native for Web
\ No newline at end of file diff --git a/docs/docs/unstable-apis/index.html b/docs/docs/unstable-apis/index.html new file mode 100644 index 00000000..d230ae6a --- /dev/null +++ b/docs/docs/unstable-apis/index.html @@ -0,0 +1,3 @@ +Unstable APIs // React Native for Web

Unstable APIs

The following APIs are unstable and subject to breaking changes. Use at your own risk.

Use with existing React DOM components #

React Native for Web exports a web-specific module called unstable_createElement, which can be used to wrap React DOM components. This allows you to use React Native’s accessibility and style optimizations. Since this is a web-specific export it should always be imported from the react-native-web package.

In the example below, Video will now accept common React Native props such as accessibilityLabel, accessible, style, and even the Responder event props.

import { unstable_createElement } from 'react-native-web';
const Video = (props) => unstable_createElement('video', props);

This also works with composite components defined in your existing component gallery or dependencies (live example).

import RaisedButton from 'material-ui/RaisedButton';
import { unstable_createElement } from 'react-native-web';
import { StyleSheet } from 'react-native';

const CustomButton = (props) => unstable_createElement(RaisedButton, {
...props,
style: [ styles.button, props.style ]
});

const styles = StyleSheet.create({
button: {
padding: 20
}
});

And unstable_createElement can be used as drop-in replacement for React.createElement:

/* @jsx unstable_createElement */
import { unstable_createElement } from 'react-native-web';
const Video = (props) => <video {...props} style={[ { marginVertical: 10 }, props.style ]} />

Remember that React Native styles are not the same as React DOM styles, and care needs to be taken not to pass React DOM styles into your React Native wrapped components.

Use as a library framework #

The React Native (for Web) building blocks can be used to create higher-level components and abstractions. In the example below, a styled function provides an API inspired by styled-components (live example).

import { unstable_createElement } from 'react-native-web';
import { StyleSheet } from 'react-native';

/**
* styled API
*/

const styled = (Component, styler) => {
const isDOMComponent = typeof Component === 'string';

class Styled extends React.Component {
static contextTypes = {
getTheme: React.PropTypes.func
};

render() {
const theme = this.context.getTheme && this.context.getTheme();
const localProps = { ...this.props, theme };
const nextProps = { ...this.props }
const style = typeof styler === 'function' ? styler(localProps) : styler;
nextProps.style = [ style, this.props.style ];

return (
isDOMComponent
? unstable_createElement(Component, nextProps)
: <Component {...nextProps} />
);
}
}
return Styled;
}

const styles = StyleSheet.create({
container: {
alignItems: 'center',
backgroundColor: '#2196F3',
flex: 1,
justifyContent: 'center'
}
});

const StyledView = styled(View, styles.container);
Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/use-color-scheme/index.html b/docs/docs/use-color-scheme/index.html new file mode 100644 index 00000000..704370a3 --- /dev/null +++ b/docs/docs/use-color-scheme/index.html @@ -0,0 +1,3 @@ +useColorScheme // React Native for Web

useColorScheme

The useColorScheme React hook provides and subscribes to color scheme updates from the Appearance module.

The return value indicates the current user preferred color scheme. The value may be updated later, either through direct user action (e.g., theme selection in device settings) or on a schedule (e.g., light and dark themes that follow the day/night cycle).

import { useColorScheme } from 'react-native';
const colorScheme = useColorScheme();

API #

Return value #

useColorScheme returns the color scheme value.

colorScheme "dark" | "light" | null

A string representing the color scheme.

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/use-window-dimensions/index.html b/docs/docs/use-window-dimensions/index.html new file mode 100644 index 00000000..1825dfbe --- /dev/null +++ b/docs/docs/use-window-dimensions/index.html @@ -0,0 +1,3 @@ +useWindowDimensions // React Native for Web

useWindowDimensions

The useWindowDimensions React hook provides and subscribes to window size changes from the Dimensions module.

useWindowDimensions automatically updates width and height values when viewport size changes.

import { useWindowDimensions } from 'react-native';
const { height, scale, width } = useWindowDimensions();

API #

Return value #

useWindowDimensions returns the window dimension object.

height number

The height in pixels of the app viewport.

scale number

The pixel ratio of the device your app is running on.

width number

The width in pixels of the app viewport.

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/vibration/index.html b/docs/docs/vibration/index.html new file mode 100644 index 00000000..fc5ddd76 --- /dev/null +++ b/docs/docs/vibration/index.html @@ -0,0 +1,3 @@ +Vibration // React Native for Web

Vibration

Vibration is described as a pattern of on-off pulses, which may be of varying lengths.

The vibration pattern may consist of either a single integer, describing the number of milliseconds to vibrate, or an array of integers describing a pattern of vibrations and pauses. Vibration is controlled with a single method: Vibration.vibrate().

import { Vibration } from 'react-native';

API #

Static methods #

cancel () => void

Stop the vibration

vibrate (number | Array<number>) => void

Start the vibration pattern

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/docs/view/index.html b/docs/docs/view/index.html new file mode 100644 index 00000000..8baf455c --- /dev/null +++ b/docs/docs/view/index.html @@ -0,0 +1,3 @@ +View // React Native for Web

View

The fundamental layout primitive.

View uses a flexbox column layout by default. Every instance of View uses relative positioning by default and the zIndex can only be used to control the relative Z-axis stacking of siblings within their parent.

Raw text nodes are not allowed as children of View. A View nested within a Text will render inline without altering its display or that of its children.

import { View } from 'react-native';

<View {...props}>{children}</View>;

Did you know? View elements do not support text content or text styles. Style properties like fontFamily are only supported on Text and TextInput elements.


API #

Props #

...AccessibilityProps

The accessibility props.

...ClickProps

The click props.

...FocusProps

The focus props.

...KeyboardProps

The keyboard props.

...ResponderProps

The responder props.

children any

The children of a View element can be other elements and must not include strings (or components that render down to strings).

dataSet ?Object

Equivalent to HTMLElement.dataset.

dir ?("ltr" | "rtl")

Equivalent to HTMLElement.dir

focusable ?boolean

Set whether the view can receive keyboard focus.

href ?string

If href is defined, the view is rendered as an anchor tag pointing to this URL.

hrefAttrs ?Object

If href is defined, this prop defines related attributes to include on the anchor (e.g., download, rel, target) which may modify its behavior.

nativeID ?string

Equivalent to HTMLElement.id.

onLayout ?({ nativeEvent: { layout: { x, y, width, height } } }) => void

This is invoked when a component is mounted and when its layout changes. x and y are the offsets from the parent node.

pointerEvents ?("all" | "none" | "box-only" | "box-none")

Equivalent to CSS pointer-events with 2 additional values. A value of "box-none" preserves pointer events on the element’s children; "box-only" disables pointer events on the element’s children.

style ?Style

Set the styles of the view.

testID ?string

Set the test selector label (via data-testid).


Examples #

Updated
Edit
React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/index.html b/docs/index.html new file mode 100644 index 00000000..0e83b325 --- /dev/null +++ b/docs/index.html @@ -0,0 +1 @@ +React Native for Web

React Native for Web

React Native Components and APIs on the Web

React Native for Web is an accessible implementation of React Native's Components and APIs that is interoperable with React DOM.

  • Accessible HTML. Support different devices and input modes, render semantic tags.
  • High-quality interactions. Support gestures and multiple input modes (touch, mouse, keyboard).
  • Reliable styles. Rely on scoped styles and automatic vendor-prefixing. Support RTL layouts.
  • Responsive containers. Respond to element resize events.
  • Incremental adoption. Interoperates with existing React DOM components. Bundle only what you use.

Try it out!

You can try React Native for Web from your browser using the official template on CodeSandbox.

Fork the template and create your own app without leaving the browser.

Did you know? React Native for Web is used in production web apps by Twitter, Flipkart, Uber, Major League Soccer, and many others. It also powers web support in multi-platform React projects such as Expo, React Native Elements, React Native Paper, and React Native Base.

React Native for WebCopyright © Nicolas Gallagher and Facebook Inc.
\ No newline at end of file diff --git a/docs/static/logo.svg b/docs/static/logo.svg new file mode 100644 index 00000000..6bde4e74 --- /dev/null +++ b/docs/static/logo.svg @@ -0,0 +1 @@ +