From ce0c74ce08b74c40d0db7bd48b7baf50a00da95e Mon Sep 17 00:00:00 2001 From: Website Deployment Script Date: Fri, 24 Jun 2016 22:08:42 +0000 Subject: [PATCH] Updated docs for next --- releases/next/docs/accessibility.html | 2 +- releases/next/docs/actionsheetios.html | 2 +- releases/next/docs/activityindicator.html | 2 +- releases/next/docs/alert.html | 2 +- releases/next/docs/alertios.html | 2 +- .../docs/android-building-from-source.html | 2 +- .../next/docs/android-ui-performance.html | 2 +- releases/next/docs/animated.html | 10 +- releases/next/docs/animations.html | 2 +- releases/next/docs/appregistry.html | 4 +- releases/next/docs/appstate.html | 4 +- releases/next/docs/asyncstorage.html | 86 ++++++++---- releases/next/docs/backandroid.html | 4 +- .../next/docs/basics-component-image.html | 2 +- .../next/docs/basics-component-listview.html | 2 +- .../docs/basics-component-scrollview.html | 2 +- releases/next/docs/basics-component-text.html | 2 +- .../next/docs/basics-component-textinput.html | 2 +- releases/next/docs/basics-component-view.html | 2 +- releases/next/docs/basics-components.html | 2 +- releases/next/docs/basics-dimensions.html | 2 +- releases/next/docs/basics-layout.html | 79 ----------- releases/next/docs/cameraroll.html | 2 +- releases/next/docs/clipboard.html | 2 +- releases/next/docs/colors.html | 2 +- releases/next/docs/communication-ios.html | 2 +- releases/next/docs/datepickerandroid.html | 4 +- releases/next/docs/datepickerios.html | 2 +- releases/next/docs/debugging.html | 2 +- releases/next/docs/dimensions.html | 2 +- releases/next/docs/direct-manipulation.html | 2 +- releases/next/docs/drawerlayoutandroid.html | 4 +- releases/next/docs/flexbox.html | 62 ++++++++- releases/next/docs/geolocation.html | 4 +- .../next/docs/gesture-responder-system.html | 2 +- releases/next/docs/getting-started.html | 2 +- releases/next/docs/handling-touches.html | 2 +- releases/next/docs/image.html | 96 +++++++++---- releases/next/docs/images.html | 2 +- .../docs/integration-with-existing-apps.html | 2 +- releases/next/docs/intentandroid.html | 2 +- releases/next/docs/interactionmanager.html | 4 +- .../next/docs/javascript-environment.html | 2 +- releases/next/docs/layout-props.html | 127 +++++++++++++++++ releases/next/docs/layoutanimation.html | 2 +- releases/next/docs/linking-libraries-ios.html | 2 +- releases/next/docs/linking.html | 6 +- releases/next/docs/listview.html | 4 +- releases/next/docs/listviewdatasource.html | 6 +- releases/next/docs/mapview.html | 2 +- releases/next/docs/modal.html | 2 +- releases/next/docs/more-resources.html | 2 +- .../next/docs/native-components-android.html | 2 +- releases/next/docs/native-components-ios.html | 2 +- .../next/docs/native-modules-android.html | 2 +- releases/next/docs/native-modules-ios.html | 2 +- releases/next/docs/nativemethodsmixin.html | 6 +- releases/next/docs/navigation.html | 128 ------------------ releases/next/docs/navigator-comparison.html | 125 +++++++++++++++-- releases/next/docs/navigator.html | 10 +- releases/next/docs/navigatorios.html | 6 +- releases/next/docs/netinfo.html | 6 +- releases/next/docs/network.html | 2 +- releases/next/docs/panresponder.html | 2 +- releases/next/docs/performance.html | 2 +- releases/next/docs/picker.html | 2 +- releases/next/docs/pickerios.html | 2 +- releases/next/docs/pixelratio.html | 6 +- .../next/docs/platform-specific-code.html | 2 +- releases/next/docs/progressbarandroid.html | 2 +- releases/next/docs/progressviewios.html | 2 +- releases/next/docs/pushnotificationios.html | 12 +- releases/next/docs/refreshcontrol.html | 2 +- .../next/docs/running-on-device-android.html | 2 +- releases/next/docs/running-on-device-ios.html | 2 +- .../next/docs/running-on-simulator-ios.html | 2 +- releases/next/docs/scrollview.html | 2 +- releases/next/docs/segmentedcontrolios.html | 2 +- releases/next/docs/shadow-props.html | 19 +++ releases/next/docs/shadowproptypesios.html | 19 --- releases/next/docs/signed-apk-android.html | 2 +- releases/next/docs/slider.html | 2 +- releases/next/docs/sliderios.html | 2 +- releases/next/docs/statusbar.html | 2 +- releases/next/docs/statusbarios.html | 2 +- releases/next/docs/style.html | 2 +- releases/next/docs/stylesheet.html | 2 +- releases/next/docs/switch.html | 2 +- releases/next/docs/tabbarios-item.html | 2 +- releases/next/docs/tabbarios.html | 2 +- releases/next/docs/testing.html | 2 +- releases/next/docs/text.html | 2 +- releases/next/docs/textinput.html | 119 ++++++++++++---- releases/next/docs/timepickerandroid.html | 4 +- releases/next/docs/timers.html | 2 +- releases/next/docs/toastandroid.html | 2 +- releases/next/docs/toolbarandroid.html | 2 +- releases/next/docs/touchablehighlight.html | 2 +- .../next/docs/touchablenativefeedback.html | 6 +- releases/next/docs/touchableopacity.html | 2 +- .../next/docs/touchablewithoutfeedback.html | 2 +- releases/next/docs/transforms.html | 2 +- releases/next/docs/troubleshooting.html | 2 +- releases/next/docs/upgrading.html | 2 +- releases/next/docs/vibration.html | 6 +- releases/next/docs/vibrationios.html | 4 +- releases/next/docs/view.html | 2 +- releases/next/docs/viewpagerandroid.html | 2 +- releases/next/docs/webview.html | 4 +- 109 files changed, 674 insertions(+), 464 deletions(-) delete mode 100644 releases/next/docs/basics-layout.html create mode 100644 releases/next/docs/layout-props.html delete mode 100644 releases/next/docs/navigation.html create mode 100644 releases/next/docs/shadow-props.html delete mode 100644 releases/next/docs/shadowproptypesios.html diff --git a/releases/next/docs/accessibility.html b/releases/next/docs/accessibility.html index 0eebece622c..903ba101d39 100644 --- a/releases/next/docs/accessibility.html +++ b/releases/next/docs/accessibility.html @@ -1,4 +1,4 @@ -Accessibility – React Native | A framework for building native apps using React

Accessibility #

Edit on GitHub

Native App Accessibility (iOS and Android) #

Both iOS and Android provide APIs for making apps accessible to people with disabilities. In addition, both platforms provide bundled assistive technologies, like the screen readers VoiceOver (iOS) and TalkBack (Android) for the visually impaired. Similarly, in React Native we have included APIs designed to provide developers with support for making apps more accessible. Take note, iOS and Android differ slightly in their approaches, and thus the React Native implementations may vary by platform.

Making Apps Accessible #

Accessibility properties #

accessible (iOS, Android) #

When true, indicates that the view is an accessibility element. When a view is an accessibility element, it groups its children into a single selectable component. By default, all touchable elements are accessible.

On Android, ‘accessible={true}’ property for a react-native View will be translated into native ‘focusable={true}’.

<View accessible={true}> +Accessibility – React Native | A framework for building native apps using React

Accessibility #

Edit on GitHub

Native App Accessibility (iOS and Android) #

Both iOS and Android provide APIs for making apps accessible to people with disabilities. In addition, both platforms provide bundled assistive technologies, like the screen readers VoiceOver (iOS) and TalkBack (Android) for the visually impaired. Similarly, in React Native we have included APIs designed to provide developers with support for making apps more accessible. Take note, iOS and Android differ slightly in their approaches, and thus the React Native implementations may vary by platform.

Making Apps Accessible #

Accessibility properties #

accessible (iOS, Android) #

When true, indicates that the view is an accessibility element. When a view is an accessibility element, it groups its children into a single selectable component. By default, all touchable elements are accessible.

On Android, ‘accessible={true}’ property for a react-native View will be translated into native ‘focusable={true}’.

<View accessible={true}> <Text>text one</Text> <Text>text two</Text> </View>

In the above example, we can't get accessibility focus separately on 'text one' and 'text two'. Instead we get focus on a parent view with 'accessible' property.

accessibilityLabel (iOS, Android) #

When a view is marked as accessible, it is a good practice to set an accessibilityLabel on the view, so that people who use VoiceOver know what element they have selected. VoiceOver will read this string when a user selects the associated element.

To use, set the accessibilityLabel property to a custom string on your View:

<TouchableOpacity accessible={true} accessibilityLabel={'Tap me!'} onPress={this._onPress}> diff --git a/releases/next/docs/actionsheetios.html b/releases/next/docs/actionsheetios.html index 495a0376edf..c007a82143a 100644 --- a/releases/next/docs/actionsheetios.html +++ b/releases/next/docs/actionsheetios.html @@ -1,4 +1,4 @@ -ActionSheetIOS – React Native | A framework for building native apps using React

ActionSheetIOS #

Edit on GitHub

Methods #

static showActionSheetWithOptions(options, callback) #

Display an iOS action sheet. The options object must contain one or more +ActionSheetIOS – React Native | A framework for building native apps using React

ActionSheetIOS #

Edit on GitHub

Methods #

static showActionSheetWithOptions(options, callback) #

Display an iOS action sheet. The options object must contain one or more of:

  • options (array of strings) - a list of button titles (required)
  • cancelButtonIndex (int) - index of cancel button in options
  • destructiveButtonIndex (int) - index of destructive button in options
  • title (string) - a title to show above the action sheet
  • message (string) - a message to show below the title

static showShareActionSheetWithOptions(options, failureCallback, successCallback) #

Display the iOS share sheet. The options object should contain one or both of message and url and can additionally have a subject or excludedActivityTypes:

  • url (string) - a URL to share
  • message (string) - a message to share
  • subject (string) - a subject for the message
  • excludedActivityTypes (array) - the activites to exclude from the ActionSheet

NOTE: if url points to a local file, or is a base64-encoded diff --git a/releases/next/docs/activityindicator.html b/releases/next/docs/activityindicator.html index 34c7a559d84..b5128c3eb8d 100644 --- a/releases/next/docs/activityindicator.html +++ b/releases/next/docs/activityindicator.html @@ -1,4 +1,4 @@ -ActivityIndicator – React Native | A framework for building native apps using React

ActivityIndicator #

Edit on GitHub

Displays a circular loading indicator.

Props #

animating bool #

Whether to show the indicator (true, the default) or hide it (false).

color color #

The foreground color of the spinner (default is gray).

size enum('small', 'large') #

Size of the indicator. Small has a height of 20, large has a height of 36. +ActivityIndicator – React Native | A framework for building native apps using React

ActivityIndicator #

Edit on GitHub

Displays a circular loading indicator.

Props #

animating bool #

Whether to show the indicator (true, the default) or hide it (false).

color color #

The foreground color of the spinner (default is gray).

size enum('small', 'large') #

Size of the indicator. Small has a height of 20, large has a height of 36. Other sizes can be obtained using a scale transform.

ioshidesWhenStopped bool #

Whether the indicator should hide when not animating (true by default).

Examples #

Edit on GitHub
'use strict'; const React = require('react'); diff --git a/releases/next/docs/alert.html b/releases/next/docs/alert.html index e7003e22557..67a3a72c132 100644 --- a/releases/next/docs/alert.html +++ b/releases/next/docs/alert.html @@ -1,4 +1,4 @@ -Alert – React Native | A framework for building native apps using React

Alert #

Edit on GitHub

Launches an alert dialog with the specified title and message.

Optionally provide a list of buttons. Tapping any button will fire the +Alert – React Native | A framework for building native apps using React

Alert #

Edit on GitHub

Launches an alert dialog with the specified title and message.

Optionally provide a list of buttons. Tapping any button will fire the respective onPress callback and dismiss the alert. By default, the only button will be an 'OK' button.

This is an API that works both on iOS and Android and can show static alerts. To show an alert that prompts the user to enter some information, diff --git a/releases/next/docs/alertios.html b/releases/next/docs/alertios.html index 9988eae4623..6dbf615bb0f 100644 --- a/releases/next/docs/alertios.html +++ b/releases/next/docs/alertios.html @@ -1,4 +1,4 @@ -AlertIOS – React Native | A framework for building native apps using React

AlertIOS #

Edit on GitHub

AlertIOS provides functionality to create an iOS alert dialog with a +AlertIOS – React Native | A framework for building native apps using React

AlertIOS #

Edit on GitHub

AlertIOS provides functionality to create an iOS alert dialog with a message or create a prompt for user input.

Creating an iOS alert:

AlertIOS.alert( 'Sync Complete', 'All your data are belong to us.' diff --git a/releases/next/docs/android-building-from-source.html b/releases/next/docs/android-building-from-source.html index 8ddcf100145..8d13a107e79 100644 --- a/releases/next/docs/android-building-from-source.html +++ b/releases/next/docs/android-building-from-source.html @@ -1,4 +1,4 @@ -Building React Native from source – React Native | A framework for building native apps using React

Building React Native from source #

Edit on GitHub

You will need to build React Native from source if you want to work on a new feature/bug fix, try out the latest features which are not released yet, or maintain your own fork with patches that cannot be merged to the core.

Prerequisites #

Assuming you have the Android SDK installed, run android to open the Android SDK Manager.

Make sure you have the following installed:

  1. Android SDK version 23 (compileSdkVersion in build.gradle)
  2. SDK build tools version 23.0.1 (buildToolsVersion in build.gradle)
  3. Local Maven repository for Support Libraries (formerly Android Support Repository) >= 17 (for Android Support Library)
  4. Android NDK (download links and installation instructions below)

Point Gradle to your Android SDK: either have $ANDROID_SDK and $ANDROID_NDK defined, or create a local.properties file in the root of your react-native checkout with the following contents:

sdk.dir=absolute_path_to_android_sdk +Building React Native from source – React Native | A framework for building native apps using React

Building React Native from source #

Edit on GitHub

You will need to build React Native from source if you want to work on a new feature/bug fix, try out the latest features which are not released yet, or maintain your own fork with patches that cannot be merged to the core.

Prerequisites #

Assuming you have the Android SDK installed, run android to open the Android SDK Manager.

Make sure you have the following installed:

  1. Android SDK version 23 (compileSdkVersion in build.gradle)
  2. SDK build tools version 23.0.1 (buildToolsVersion in build.gradle)
  3. Local Maven repository for Support Libraries (formerly Android Support Repository) >= 17 (for Android Support Library)
  4. Android NDK (download links and installation instructions below)

Point Gradle to your Android SDK: either have $ANDROID_SDK and $ANDROID_NDK defined, or create a local.properties file in the root of your react-native checkout with the following contents:

sdk.dir=absolute_path_to_android_sdk ndk.dir=absolute_path_to_android_ndk

Example:

sdk.dir=/Users/your_unix_name/android-sdk-macosx ndk.dir=/Users/your_unix_name/android-ndk/android-ndk-r10e

Download links for Android NDK #

  1. Mac OS (64-bit) - http://dl.google.com/android/repository/android-ndk-r10e-darwin-x86_64.zip
  2. Linux (64-bit) - http://dl.google.com/android/repository/android-ndk-r10e-linux-x86_64.zip
  3. Windows (64-bit) - http://dl.google.com/android/repository/android-ndk-r10e-windows-x86_64.zip
  4. Windows (32-bit) - http://dl.google.com/android/repository/android-ndk-r10e-windows-x86.zip

You can find further instructions on the official page.

Building the source #

1. Installing the fork #

First, you need to install react-native from your fork. For example, to install the master branch from the official repo, run the following:

npm install --save github:facebook/react-native#master

Alternatively, you can clone the repo to your node_modules directory and run npm install inside the cloned repo.

2. Adding gradle dependencies #

Add gradle-download-task as dependency in android/build.gradle:

... dependencies { diff --git a/releases/next/docs/android-ui-performance.html b/releases/next/docs/android-ui-performance.html index 2d1e945dff9..2b9ba9c8a98 100644 --- a/releases/next/docs/android-ui-performance.html +++ b/releases/next/docs/android-ui-performance.html @@ -1,4 +1,4 @@ -Profiling Android UI Performance – React Native | A framework for building native apps using React

Profiling Android UI Performance #

Edit on GitHub

We try our best to deliver buttery-smooth UI performance by default, but sometimes that just isn't possible. Remember, Android supports 10k+ different phones and is generalized to support software rendering: the framework architecture and need to generalize across many hardware targets unfortunately means you get less for free relative to iOS. But sometimes, there are things you can improve (and many times it's not native code's fault at all!).

The first step for debugging this jank is to answer the fundamental question of where your time is being spent during each 16ms frame. For that, we'll be using a standard Android profiling tool called systrace. But first...

Make sure that JS dev mode is OFF!

You should see __DEV__ === false, development-level warning are OFF, performance optimizations are ON in your application logs (which you can view using adb logcat)

Profiling with Systrace #

Systrace is a standard Android marker-based profiling tool (and is installed when you install the Android platform-tools package). Profiled code blocks are surrounded by markers start/end markers which are then visualized in a colorful chart format. Both the Android SDK and React Native framework provide standard markers that you can visualize.

Collecting a trace #

NOTE:

Systrace support was added in react-native v0.15. You will need to build with that version to collect a trace.

First, connect a device that exhibits the stuttering you want to investigate to your computer via USB and get it to the point right before the navigation/animation you want to profile. Run systrace as follows

$ <path_to_android_sdk>/platform-tools/systrace/systrace.py --time=10 -o trace.html sched gfx view -a <your_package_name>

A quick breakdown of this command:

  • time is the length of time the trace will be collected in seconds
  • sched, gfx, and view are the android SDK tags (collections of markers) we care about: sched gives you information about what's running on each core of your phone, gfx gives you graphics info such as frame boundaries, and view gives you information about measure, layout, and draw passes
  • -a <your_package_name> enables app-specific markers, specifically the ones built into the React Native framework. your_package_name can be found in the AndroidManifest.xml of your app and looks like com.example.app

Once the trace starts collecting, perform the animation or interaction you care about. At the end of the trace, systrace will give you a link to the trace which you can open in your browser.

Reading the trace #

After opening the trace in your browser (preferably Chrome), you should see something like this:

Example

HINT: Use the WASD keys to strafe and zoom

Enable VSync highlighting #

The first thing you should do is highlight the 16ms frame boundaries if you haven't already done that. Check this checkbox at the top right of the screen:

Enable VSync Highlighting

You should see zebra stripes as in the screenshot above. If you don't, try profiling on a different device: Samsung has been known to have issues displaying vsyncs while the Nexus series is generally pretty reliable.

Find your process #

Scroll until you see (part of) the name of your package. In this case, I was profiling com.facebook.adsmanager, which shows up as book.adsmanager because of silly thread name limits in the kernel.

On the left side, you'll see a set of threads which correspond to the timeline rows on the right. There are three/four threads we care about for our purposes: the UI thread (which has your package name or the name UI Thread), mqt_js and mqt_native_modules. If you're running on Android 5+, we also care about the Render Thread.

UI Thread #

This is where standard android measure/layout/draw happens. The thread name on the right will be your package name (in my case book.adsmanager) or UI Thread. The events that you see on this thread should look something like this and have to do with Choreographer, traversals, and DispatchUI:

UI Thread Example

JS Thread #

This is where JS is executed. The thread name will be either mqt_js or <...> depending on how cooperative the kernel on your device is being. To identify it if it doesn't have a name, look for things like JSCall, Bridge.executeJSCall, etc:

JS Thread Example

Native Modules Thread #

This is where native module calls (e.g. the UIManager) are executed. The thread name will be either mqt_native_modules or <...>. To identify it in the latter case, look for things like NativeCall, callJavaModuleMethod, and onBatchComplete:

Native Modules Thread Example

Bonus: Render Thread #

If you're using Android L (5.0) and up, you will also have a render thread in your application. This thread generates the actual OpenGL commands used to draw your UI. The thread name will be either RenderThread or <...>. To identify it in the latter case, look for things like DrawFrame and queueBuffer:

Render Thread Example

Identifying a culprit #

A smooth animation should look something like the following:

Smooth Animation

Each change in color is a frame -- remember that in order to display a frame, all our UI work needs to be done by the end of that 16ms period. Notice that no thread is working close to the frame boundary. An application rendering like this is rendering at 60FPS.

If you noticed chop, however, you might see something like this:

Choppy Animation from JS

Notice that the JS thread is executing basically all the time, and across frame boundaries! This app is not rendering at 60FPS. In this case, the problem lies in JS.

You might also see something like this:

Choppy Animation from UI

In this case, the UI and render threads are the ones that have work crossing frame boundaries. The UI that we're trying to render on each frame is requiring too much work to be done. In this case, the problem lies in the native views being rendered.

At this point, you'll have some very helpful information to inform your next steps.

JS Issues #

If you identified a JS problem, look for clues in the specific JS that you're executing. In the scenario above, we see RCTEventEmitter being called multiple times per frame. Here's a zoom-in of the JS thread from the trace above:

Too much JS

This doesn't seem right. Why is it being called so often? Are they actually different events? The answers to these questions will probably depend on your product code. And many times, you'll want to look into shouldComponentUpdate.

TODO: Add more tools for profiling JS

Native UI Issues #

If you identified a native UI problem, there are usually two scenarios:

  1. the UI you're trying to draw each frame involves to much work on the GPU, or
  2. You're constructing new UI during the animation/interaction (e.g. loading in new content during a scroll).

Too much GPU work #

In the first scenario, you'll see a trace that has the UI thread and/or Render Thread looking like this:

Overloaded GPU

Notice the long amount of time spent in DrawFrame that crosses frame boundaries. This is time spent waiting for the GPU to drain its command buffer from the previous frame.

To mitigate this, you should:

  • investigate using renderToHardwareTextureAndroid for complex, static content that is being animated/transformed (e.g. the Navigator slide/alpha animations)
  • make sure that you are not using needsOffscreenAlphaCompositing, which is disabled by default, as it greatly increases the per-frame load on the GPU in most cases.

If these don't help and you want to dig deeper into what the GPU is actually doing, you can check out Tracer for OpenGL ES.

Creating new views on the UI thread #

In the second scenario, you'll see something more like this:

Creating Views

Notice that first the JS thread thinks for a bit, then you see some work done on the native modules thread, followed by an expensive traversal on the UI thread.

There isn't an easy way to mitigate this unless you're able to postpone creating new UI until after the interaction, or you are able to simplify the UI you're creating. The react native team is working on a infrastructure level solution for this that will allow new UI to be created and configured off the main thread, allowing the interaction to continue smoothly.

Still stuck? #

If you are confused or stuck, please post ask on Stack Overflow with the react-native tag. If you are unable to get a response there, or find an issue with a core component, please File a Github issue.

© 2016 Facebook Inc.

Profiling Android UI Performance #

Edit on GitHub

We try our best to deliver buttery-smooth UI performance by default, but sometimes that just isn't possible. Remember, Android supports 10k+ different phones and is generalized to support software rendering: the framework architecture and need to generalize across many hardware targets unfortunately means you get less for free relative to iOS. But sometimes, there are things you can improve (and many times it's not native code's fault at all!).

The first step for debugging this jank is to answer the fundamental question of where your time is being spent during each 16ms frame. For that, we'll be using a standard Android profiling tool called systrace. But first...

Make sure that JS dev mode is OFF!

You should see __DEV__ === false, development-level warning are OFF, performance optimizations are ON in your application logs (which you can view using adb logcat)

Profiling with Systrace #

Systrace is a standard Android marker-based profiling tool (and is installed when you install the Android platform-tools package). Profiled code blocks are surrounded by markers start/end markers which are then visualized in a colorful chart format. Both the Android SDK and React Native framework provide standard markers that you can visualize.

Collecting a trace #

NOTE:

Systrace support was added in react-native v0.15. You will need to build with that version to collect a trace.

First, connect a device that exhibits the stuttering you want to investigate to your computer via USB and get it to the point right before the navigation/animation you want to profile. Run systrace as follows

$ <path_to_android_sdk>/platform-tools/systrace/systrace.py --time=10 -o trace.html sched gfx view -a <your_package_name>

A quick breakdown of this command:

  • time is the length of time the trace will be collected in seconds
  • sched, gfx, and view are the android SDK tags (collections of markers) we care about: sched gives you information about what's running on each core of your phone, gfx gives you graphics info such as frame boundaries, and view gives you information about measure, layout, and draw passes
  • -a <your_package_name> enables app-specific markers, specifically the ones built into the React Native framework. your_package_name can be found in the AndroidManifest.xml of your app and looks like com.example.app

Once the trace starts collecting, perform the animation or interaction you care about. At the end of the trace, systrace will give you a link to the trace which you can open in your browser.

Reading the trace #

After opening the trace in your browser (preferably Chrome), you should see something like this:

Example

HINT: Use the WASD keys to strafe and zoom

Enable VSync highlighting #

The first thing you should do is highlight the 16ms frame boundaries if you haven't already done that. Check this checkbox at the top right of the screen:

Enable VSync Highlighting

You should see zebra stripes as in the screenshot above. If you don't, try profiling on a different device: Samsung has been known to have issues displaying vsyncs while the Nexus series is generally pretty reliable.

Find your process #

Scroll until you see (part of) the name of your package. In this case, I was profiling com.facebook.adsmanager, which shows up as book.adsmanager because of silly thread name limits in the kernel.

On the left side, you'll see a set of threads which correspond to the timeline rows on the right. There are three/four threads we care about for our purposes: the UI thread (which has your package name or the name UI Thread), mqt_js and mqt_native_modules. If you're running on Android 5+, we also care about the Render Thread.

UI Thread #

This is where standard android measure/layout/draw happens. The thread name on the right will be your package name (in my case book.adsmanager) or UI Thread. The events that you see on this thread should look something like this and have to do with Choreographer, traversals, and DispatchUI:

UI Thread Example

JS Thread #

This is where JS is executed. The thread name will be either mqt_js or <...> depending on how cooperative the kernel on your device is being. To identify it if it doesn't have a name, look for things like JSCall, Bridge.executeJSCall, etc:

JS Thread Example

Native Modules Thread #

This is where native module calls (e.g. the UIManager) are executed. The thread name will be either mqt_native_modules or <...>. To identify it in the latter case, look for things like NativeCall, callJavaModuleMethod, and onBatchComplete:

Native Modules Thread Example

Bonus: Render Thread #

If you're using Android L (5.0) and up, you will also have a render thread in your application. This thread generates the actual OpenGL commands used to draw your UI. The thread name will be either RenderThread or <...>. To identify it in the latter case, look for things like DrawFrame and queueBuffer:

Render Thread Example

Identifying a culprit #

A smooth animation should look something like the following:

Smooth Animation

Each change in color is a frame -- remember that in order to display a frame, all our UI work needs to be done by the end of that 16ms period. Notice that no thread is working close to the frame boundary. An application rendering like this is rendering at 60FPS.

If you noticed chop, however, you might see something like this:

Choppy Animation from JS

Notice that the JS thread is executing basically all the time, and across frame boundaries! This app is not rendering at 60FPS. In this case, the problem lies in JS.

You might also see something like this:

Choppy Animation from UI

In this case, the UI and render threads are the ones that have work crossing frame boundaries. The UI that we're trying to render on each frame is requiring too much work to be done. In this case, the problem lies in the native views being rendered.

At this point, you'll have some very helpful information to inform your next steps.

JS Issues #

If you identified a JS problem, look for clues in the specific JS that you're executing. In the scenario above, we see RCTEventEmitter being called multiple times per frame. Here's a zoom-in of the JS thread from the trace above:

Too much JS

This doesn't seem right. Why is it being called so often? Are they actually different events? The answers to these questions will probably depend on your product code. And many times, you'll want to look into shouldComponentUpdate.

TODO: Add more tools for profiling JS

Native UI Issues #

If you identified a native UI problem, there are usually two scenarios:

  1. the UI you're trying to draw each frame involves to much work on the GPU, or
  2. You're constructing new UI during the animation/interaction (e.g. loading in new content during a scroll).

Too much GPU work #

In the first scenario, you'll see a trace that has the UI thread and/or Render Thread looking like this:

Overloaded GPU

Notice the long amount of time spent in DrawFrame that crosses frame boundaries. This is time spent waiting for the GPU to drain its command buffer from the previous frame.

To mitigate this, you should:

  • investigate using renderToHardwareTextureAndroid for complex, static content that is being animated/transformed (e.g. the Navigator slide/alpha animations)
  • make sure that you are not using needsOffscreenAlphaCompositing, which is disabled by default, as it greatly increases the per-frame load on the GPU in most cases.

If these don't help and you want to dig deeper into what the GPU is actually doing, you can check out Tracer for OpenGL ES.

Creating new views on the UI thread #

In the second scenario, you'll see something more like this:

Creating Views

Notice that first the JS thread thinks for a bit, then you see some work done on the native modules thread, followed by an expensive traversal on the UI thread.

There isn't an easy way to mitigate this unless you're able to postpone creating new UI until after the interaction, or you are able to simplify the UI you're creating. The react native team is working on a infrastructure level solution for this that will allow new UI to be created and configured off the main thread, allowing the interaction to continue smoothly.

Still stuck? #

If you are confused or stuck, please post ask on Stack Overflow with the react-native tag. If you are unable to get a response there, or find an issue with a core component, please File a Github issue.

© 2016 Facebook Inc.

Animated #

Edit on GitHub

Animations are an important part of modern UX, and the Animated +Animated – React Native | A framework for building native apps using React

Animated #

Edit on GitHub

Animations are an important part of modern UX, and the Animated library is designed to make them fluid, powerful, and easy to build and maintain.

The simplest workflow is to create an Animated.Value, hook it up to one or more style attributes of an animated component, and then drive updates either @@ -85,14 +85,14 @@ mechanism at a time. Using a new mechanism (e.g. starting a new animation, or calling setValue) will stop any previous ones.

Methods #

constructor(value) #

setValue(value) #

Directly set the value. This will stop any animations running on the value and update all the bound properties.

setOffset(offset) #

Sets an offset that is applied on top of whatever value is set, whether via setValue, an animation, or Animated.event. Useful for compensating -things like the start of a pan gesture.

flattenOffset() #

Merges the offset value into the base value and resets the offset to zero. +things like the start of a pan gesture.

flattenOffset(0) #

Merges the offset value into the base value and resets the offset to zero. The final output of the value is unchanged.

addListener(callback) #

Adds an asynchronous listener to the value so you can observe updates from animations. This is useful because there is no way to -synchronously read the value because it might be driven natively.

removeListener(id) #

removeAllListeners() #

stopAnimation(callback?) #

Stops any running animation or tracking. callback is invoked with the +synchronously read the value because it might be driven natively.

removeListener(id) #

removeAllListeners(0) #

stopAnimation(callback?) #

Stops any running animation or tracking. callback is invoked with the final value after stopping the animation, which is useful for updating state to match the animation position with layout.

interpolate(config) #

Interpolates the value before updating the property, e.g. mapping 0-1 to 0-10.

animate(animation, callback) #

Typically only used internally, but could be used by a custom Animation -class.

stopTracking() #

Typically only used internally.

track(tracking) #

Typically only used internally.

class AnimatedValueXY #

    2D Value for driving 2D animations, such as pan gestures. Almost identical +class.

stopTracking(0) #

Typically only used internally.

track(tracking) #

Typically only used internally.

class AnimatedValueXY #

    2D Value for driving 2D animations, such as pan gestures. Almost identical API to normal Animated.Value, but multiplexed. Contains two regular Animated.Values under the hood. Example:

    class DraggableView extends React.Component { constructor(props) { @@ -123,7 +123,7 @@ API to normal Animated.Value, but multiplexed. Contains two regula </Animated.View> ); } - }

    Methods #

    constructor(valueIn?) #

    setValue(value) #

    setOffset(offset) #

    flattenOffset() #

    stopAnimation(callback?) #

    addListener(callback) #

    removeListener(id) #

    getLayout() #

    Converts {x, y} into {left, top} for use in style, e.g.

    style={this.state.anim.getLayout()}

    getTranslateTransform() #

    Converts {x, y} into a useable translation transform, e.g.

    style={{ + }

    Methods #

    constructor(valueIn?) #

    setValue(value) #

    setOffset(offset) #

    flattenOffset(0) #

    stopAnimation(callback?) #

    addListener(callback) #

    removeListener(id) #

    getLayout(0) #

    Converts {x, y} into {left, top} for use in style, e.g.

    style={this.state.anim.getLayout()}

    getTranslateTransform(0) #

    Converts {x, y} into a useable translation transform, e.g.

    style={{ transform: this.state.anim.getTranslateTransform() }}

Examples #

Edit on GitHub
'use strict'; diff --git a/releases/next/docs/animations.html b/releases/next/docs/animations.html index f7f5f29f055..19c3329ef8d 100644 --- a/releases/next/docs/animations.html +++ b/releases/next/docs/animations.html @@ -1,4 +1,4 @@ -Animations – React Native | A framework for building native apps using React

Animations #

Edit on GitHub

Fluid, meaningful animations are essential to the mobile user experience. Like +Animations – React Native | A framework for building native apps using React

Animations #

Edit on GitHub

Fluid, meaningful animations are essential to the mobile user experience. Like everything in React Native, Animation APIs for React Native are currently under development, but have started to coalesce around two complementary systems: LayoutAnimation for animated global layout transactions, and Animated for diff --git a/releases/next/docs/appregistry.html b/releases/next/docs/appregistry.html index 459b41cfac1..c17eaabea62 100644 --- a/releases/next/docs/appregistry.html +++ b/releases/next/docs/appregistry.html @@ -1,4 +1,4 @@ -AppRegistry – React Native | A framework for building native apps using React

AppRegistry #

Edit on GitHub

AppRegistry is the JS entry point to running all React Native apps. App +AppRegistry – React Native | A framework for building native apps using React

AppRegistry #

Edit on GitHub

AppRegistry is the JS entry point to running all React Native apps. App root components should register themselves with AppRegistry.registerComponent, then the native system can load the bundle for the app and then actually run the app when it's ready by invoking @@ -6,7 +6,7 @@ for the app and then actually run the app when it's ready by invoking AppRegistry.unmountApplicationComponentAtRootTag with the tag that was pass into runApplication. These should always be used as a pair.

AppRegistry should be required early in the require sequence to make sure the JS execution environment is setup before other modules are -required.

Methods #

static registerConfig(config) #

static registerComponent(appKey, getComponentFunc) #

static registerRunnable(appKey, func) #

static getAppKeys() #

static runApplication(appKey, appParameters) #

static unmountApplicationComponentAtRootTag(rootTag) #

© 2016 Facebook Inc.

AppState #

Edit on GitHub

AppState can tell you if the app is in the foreground or background, +AppState – React Native | A framework for building native apps using React

AppState #

Edit on GitHub

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

AppState is frequently used to determine the intent and proper behavior when handling push notifications.

App States #

  • active - The app is running in the foreground
  • background - The app is running in the background. The user is either in another app or on the home screen
  • inactive - This is a state that occurs when transitioning between @@ -26,7 +26,7 @@ render: funct ); },

This example will only ever appear to say "Current state is: active" because the app is only visible to the user when in the active state, and the null -state will happen only momentarily.

Methods #

constructor() #

addEventListener(type, handler) #

Add a handler to AppState changes by listening to the change event type +state will happen only momentarily.

Methods #

constructor(0) #

addEventListener(type, handler) #

Add a handler to AppState changes by listening to the change event type and providing the handler

TODO: now that AppState is a subclass of NativeEventEmitter, we could deprecate addEventListener and removeEventListener and just use addListener and listener.remove() directly. That will be a breaking change though, as both diff --git a/releases/next/docs/asyncstorage.html b/releases/next/docs/asyncstorage.html index de1e964ed56..0b73266c31e 100644 --- a/releases/next/docs/asyncstorage.html +++ b/releases/next/docs/asyncstorage.html @@ -1,20 +1,35 @@ -AsyncStorage – React Native | A framework for building native apps using React

AsyncStorage #

Edit on GitHub

AsyncStorage is a simple, asynchronous, persistent, key-value storage -system that is global to the app. It should be used instead of LocalStorage.

It is recommended that you use an abstraction on top of AsyncStorage instead -of AsyncStorage directly for anything more than light usage since it -operates globally.

On iOS, AsyncStorage is backed by native code that stores small values in a serialized -dictionary and larger values in separate files. On Android, AsyncStorage will use either -RocksDB or SQLite based on what is available. This JS code is a simple facade that -provides a clear JS API, real Error objects, and simple non-multi functions. Each -method returns a Promise object.

Methods #

static getItem(key, callback?) #

Fetches key and passes the result to callback, along with an Error if -there is any. Returns a Promise object.

static setItem(key, value, callback?) #

Sets value for key and calls callback on completion, along with an -Error if there is any. Returns a Promise object.

static removeItem(key, callback?) #

Returns a Promise object.

static mergeItem(key, value, callback?) #

Merges existing value with input value, assuming they are stringified json. -Returns a Promise object. Not supported by all native implementations.

Example:

let UID123_object = { +AsyncStorage – React Native | A framework for building native apps using React

AsyncStorage #

Edit on GitHub

AsyncStorage is a simple, asynchronous, persistent, key-value storage +system that is global to the app. It should be used instead of LocalStorage.

It is recommended that you use an abstraction on top of AsyncStorage +instead of AsyncStorage directly for anything more than light usage since +it operates globally.

On iOS, AsyncStorage is backed by native code that stores small values in a +serialized dictionary and larger values in separate files. On Android, +AsyncStorage will use either RocksDB or SQLite +based on what is available.

The AsyncStorage JavaScript code is a simple facade that provides a clear +JavaScript API, real Error objects, and simple non-multi functions. Each +method in the API returns a Promise object.

Persisting data:

try { + await AsyncStorage.setItem('@MySuperStore:key', 'I like to save it.'); +} catch (error) { + // Error saving data +}

Fetching data:

try { + const value = await AsyncStorage.getItem('@MySuperStore:key'); + if (value !== null){ + // We have data!! + console.log(value); + } +} catch (error) { + // Error retrieving data +}

Methods #

static getItem(key, callback?) #

Fetches an item for a key and invokes a callback upon completion. +Returns a Promise object.

Parameters:
Name and TypeDescription
key

string

Key of the item to fetch.

[callback]

?(error: ?Error, result: ?string) => void

Function that will be called with a result if found or + any error.

static setItem(key, value, callback?) #

Sets the value for a key and invokes a callback upon completion. +Returns a Promise object.

Parameters:
Name and TypeDescription
key

string

Key of the item to set.

value

string

Value to set for the key.

[callback]

?(error: ?Error) => void

Function that will be called with any error.

static removeItem(key, callback?) #

Removes an item for a key and invokes a callback upon completion. +Returns a Promise object.

Parameters:
Name and TypeDescription
key

string

Key of the item to remove.

[callback]

?(error: ?Error) => void

Function that will be called with any error.

static mergeItem(key, value, callback?) #

Merges an existing key value with an input value, assuming both values +are stringified JSON. Returns a Promise object.

NOTE: This is not supported by all native implementations.

Parameters:
Name and TypeDescription
key

string

Key of the item to modify.

value

string

New value to merge for the key.

[callback]

?(error: ?Error) => void

Function that will be called with any error.


Example:
+let UID123_object = { name: 'Chris', age: 30, traits: {hair: 'brown', eyes: 'brown'}, -}; - -// need only define what will be added or updated +}; +// You only need to define what will be added or updated let UID123_delta = { age: 31, traits: {eyes: 'blue', shoe_size: 10} @@ -24,13 +39,19 @@ AsyncStorage..mergeItem('UID123', JSON.stringify(UID123_delta), () => { AsyncStorage.getItem('UID123', (err, result) => { console.log(result); - // => {'name':'Chris','age':31,'traits':{'shoe_size':10,'hair':'brown','eyes':'blue'}} - }); + }); }); -});

static clear(callback?) #

Erases all AsyncStorage for all clients, libraries, etc. You probably -don't want to call this - use removeItem or multiRemove to clear only your -own keys instead. Returns a Promise object.

static getAllKeys(callback?) #

Gets all keys known to the app, for all callers, libraries, etc. Returns a Promise object.

Example: see multiGet for example

static flushGetRequests() #

Flushes any pending requests using a single multiget

static multiGet(keys, callback?) #

multiGet invokes callback with an array of key-value pair arrays that -matches the input format of multiSet. Returns a Promise object.

multiGet(['k1', 'k2'], cb) -> cb([['k1', 'val1'], ['k2', 'val2']])

Example:

AsyncStorage.getAllKeys((err, keys) => { +}); + +// Console log result: +// => {'name':'Chris','age':31,'traits': +// {'shoe_size':10,'hair':'brown','eyes':'blue'}}

static clear(callback?) #

Erases all AsyncStorage for all clients, libraries, etc. You probably +don't want to call this; use removeItem or multiRemove to clear only +your app's keys. Returns a Promise object.

Parameters:
Name and TypeDescription
[callback]

?(error: ?Error) => void

Function that will be called with any error.

static getAllKeys(callback?) #

Gets all keys known to your app; for all callers, libraries, etc. +Returns a Promise object.

Parameters:
Name and TypeDescription
[callback]

?(error: ?Error, keys: ?Array<string>) => void

Function that will be called the keys found and any error.

static flushGetRequests() #

Flushes any pending requests using a single batch call to get the data.

static multiGet(keys, callback?) #

This allows you to batch the fetching of items given an array of key +inputs. Your callback will be invoked with an array of corresponding +key-value pairs found:

multiGet(['k1', 'k2'], cb) -> cb([['k1', 'val1'], ['k2', 'val2']])

The method returns a Promise object.

Parameters:
Name and TypeDescription
keys

Array<string>

Array of key for the items to get.

[callback]

?(errors: ?Array<Error>, result: ?Array<Array<string>>) => void

Function that will be called with a key-value array of + the results, plus an array of any key-specific errors found.


Example:
AsyncStorage.getAllKeys((err, keys) => { AsyncStorage.multiGet(keys, (err, stores) => { stores.map((result, i, store) => { // get at each store's key/value so you can work with it @@ -38,13 +59,20 @@ matches the input format of multiSet. Returns a Promise object.

let value = store[i][1]; }); }); -});

static multiSet(keyValuePairs, callback?) #

multiSet and multiMerge take arrays of key-value array pairs that match -the output of multiGet, e.g. Returns a Promise object.

multiSet([['k1', 'val1'], ['k2', 'val2']], cb);

Example: see multiMerge for an example

static multiRemove(keys, callback?) #

Delete all the keys in the keys array. Returns a Promise object.

Example:

let keys = ['k1', 'k2']; +});

static multiSet(keyValuePairs, callback?) #

Use this as a batch operation for storing multiple key-value pairs. When +the operation completes you'll get a single callback with any errors:

multiSet([['k1', 'val1'], ['k2', 'val2']], cb);

The method returns a Promise object.

Parameters:
Name and TypeDescription
keyValuePairs

Array<Array<string>>

Array of key-value array for the items to set.

[callback]

?(errors: ?Array<Error>) => void

Function that will be called with an array of any + key-specific errors found.

static multiRemove(keys, callback?) #

Call this to batch the deletion of all keys in the keys array. Returns +a Promise object.

Parameters:
Name and TypeDescription
keys

Array<string>

Array of key for the items to delete.

[callback]

?(errors: ?Array<Error>) => void

Function that will be called an array of any key-specific + errors found.


Example:
+let keys = ['k1', 'k2']; AsyncStorage.multiRemove(keys, (err) => { // keys k1 & k2 removed, if they existed // do most stuff after removal (if you want) -});

static multiMerge(keyValuePairs, callback?) #

Merges existing values with input values, assuming they are stringified -json. Returns a Promise object.

Not supported by all native implementations.

Example:

// first user, initial values +});

static multiMerge(keyValuePairs, callback?) #

Batch operation to merge in existing and new values for a given set of +keys. This assumes that the values are stringified JSON. Returns a +Promise object.

NOTE: This is not supported by all native implementations.

Parameters:
Name and TypeDescription
keyValuePairs

Array<Array<string>>

Array of key-value array for the items to merge.

[callback]

?(errors: ?Array<Error>) => void

Function that will be called with an array of any + key-specific errors found.


Example:
+// first user, initial values let UID234_object = { name: 'Chris', age: 30, @@ -80,12 +108,14 @@ AsyncStorage.let key = store[i][0]; let val = store[i][1]; console.log(key, val); - // => UID234 {"name":"Chris","age":31,"traits":{"shoe_size":10,"hair":"brown","eyes":"blue"}} - // => UID345 {"name":"Marge","age":26,"traits":{"shoe_size":6,"hair":"blonde","eyes":"green"}} - }); + }); }); }); -});

Properties #

Examples #

Edit on GitHub
'use strict'; +}); + +// Console log results: +// => UID234 {"name":"Chris","age":31,"traits":{"shoe_size":10,"hair":"brown","eyes":"blue"}} +// => UID345 {"name":"Marge","age":26,"traits":{"shoe_size":6,"hair":"blonde","eyes":"green"}}

Examples #

Edit on GitHub
'use strict'; var React = require('react'); var ReactNative = require('react-native'); diff --git a/releases/next/docs/backandroid.html b/releases/next/docs/backandroid.html index 0ef0295fb25..f0daed15b08 100644 --- a/releases/next/docs/backandroid.html +++ b/releases/next/docs/backandroid.html @@ -1,11 +1,11 @@ -BackAndroid – React Native | A framework for building native apps using React

BackAndroid #

Edit on GitHub

Detect hardware back button presses, and programmatically invoke the default back button +BackAndroid – React Native | A framework for building native apps using React

BackAndroid #

Edit on GitHub

Detect hardware back button presses, and programmatically invoke the default back button functionality to exit the app if there are no listeners or if none of the listeners return true.

Example:

BackAndroid.addEventListener('hardwareBackPress', function() { if (!this.onMainScreen()) { this.goBack(); return true; } return false; -});

Methods #

static exitApp() #

static addEventListener(eventName, handler) #

static removeEventListener(eventName, handler) #

© 2016 Facebook Inc.

Image #

Edit on GitHub

Another basic React Native component is the Image component. Like Text, the Image component simply renders an image.

An Image is analogous to the <img> HTML tag when building websites.

The simplest way to render an image is to provide a source file to that image via the source attribute.

This example displays a checkbox Image on the device.

import React, { Component } from 'react'; +Image – React Native | A framework for building native apps using React

Image #

Edit on GitHub

Another basic React Native component is the Image component. Like Text, the Image component simply renders an image.

An Image is analogous to the <img> HTML tag when building websites.

The simplest way to render an image is to provide a source file to that image via the source attribute.

This example displays a checkbox Image on the device.

import React, { Component } from 'react'; import { AppRegistry, Image } from 'react-native'; class ImageBasics extends Component { diff --git a/releases/next/docs/basics-component-listview.html b/releases/next/docs/basics-component-listview.html index 9ebc74e1856..91efae31fdf 100644 --- a/releases/next/docs/basics-component-listview.html +++ b/releases/next/docs/basics-component-listview.html @@ -1,4 +1,4 @@ -ListView – React Native | A framework for building native apps using React

ListView #

Edit on GitHub

On mobile devices, lists are a core element in many applications. The ListView component is a special type of View that displays a vertically scrolling list of changing, but similarly structured, data.

ListView works best for possibly lengthy datasources (e.g., from an endpoint or database), where the number of items may not be known a priori.

Unlike the more generic ScrollView, the ListView only renders elements that are currently showing on the screen, not all the elements at once.

The ListView component requires two properties, dataSource and renderRow. dataSource is the source of information for the list. renderRow takes one item from the source and returns a formatted component to render.

This example creates a simple ListView of hardcoded data. It first initializes the dataSource that will be used to populate the ListView. Each item in the dataSource is then rendered as a Text component. Finally it renders the ListView and all Text components.

A rowHasChanged function is required to use ListView. Here we just say a row has changed if the row we are on is not the same as the previous row.

import React, { Component } from 'react'; +ListView – React Native | A framework for building native apps using React

ListView #

Edit on GitHub

On mobile devices, lists are a core element in many applications. The ListView component is a special type of View that displays a vertically scrolling list of changing, but similarly structured, data.

ListView works best for possibly lengthy datasources (e.g., from an endpoint or database), where the number of items may not be known a priori.

Unlike the more generic ScrollView, the ListView only renders elements that are currently showing on the screen, not all the elements at once.

The ListView component requires two properties, dataSource and renderRow. dataSource is the source of information for the list. renderRow takes one item from the source and returns a formatted component to render.

This example creates a simple ListView of hardcoded data. It first initializes the dataSource that will be used to populate the ListView. Each item in the dataSource is then rendered as a Text component. Finally it renders the ListView and all Text components.

A rowHasChanged function is required to use ListView. Here we just say a row has changed if the row we are on is not the same as the previous row.

import React, { Component } from 'react'; import { AppRegistry, ListView, Text, View } from 'react-native'; class ListViewBasics extends Component { diff --git a/releases/next/docs/basics-component-scrollview.html b/releases/next/docs/basics-component-scrollview.html index f86b74c1d6e..fc40bcf8433 100644 --- a/releases/next/docs/basics-component-scrollview.html +++ b/releases/next/docs/basics-component-scrollview.html @@ -1,4 +1,4 @@ -ScrollView – React Native | A framework for building native apps using React

ScrollView #

Edit on GitHub

Given the screen sizes of mobile devices, the ability to scroll through data is generally paramount for a proper usability experience.

The ScrollView is a generic scrolling container that can host multiple components and views. The scrollable items need not be homogenous, and you can scroll both vertically and horizontally (by setting the horizontal property).

ScrollView works best to present a list of short, static items of a known quantity. All the elements and views of a ScrollView are rendered a priori, even if they are not currently shown on the screen. Contrast this with a ListView, which render only those views that are on the screen and remove views that go off-screen.

TextView and ListView are specialized scrollable containers.

This contrived example creates a horizontal ScrollView with a static amount of heterogenous elements (images and text).

import React, { Component } from 'react'; +ScrollView – React Native | A framework for building native apps using React

ScrollView #

Edit on GitHub

Given the screen sizes of mobile devices, the ability to scroll through data is generally paramount for a proper usability experience.

The ScrollView is a generic scrolling container that can host multiple components and views. The scrollable items need not be homogenous, and you can scroll both vertically and horizontally (by setting the horizontal property).

ScrollView works best to present a list of short, static items of a known quantity. All the elements and views of a ScrollView are rendered a priori, even if they are not currently shown on the screen. Contrast this with a ListView, which render only those views that are on the screen and remove views that go off-screen.

TextView and ListView are specialized scrollable containers.

This contrived example creates a horizontal ScrollView with a static amount of heterogenous elements (images and text).

import React, { Component } from 'react'; import{ AppRegistry, ScrollView, Image, Text, View } from 'react-native' class ScrollViewBasics extends Component { diff --git a/releases/next/docs/basics-component-text.html b/releases/next/docs/basics-component-text.html index e9342ddae72..7902c3851d2 100644 --- a/releases/next/docs/basics-component-text.html +++ b/releases/next/docs/basics-component-text.html @@ -1,4 +1,4 @@ -Text – React Native | A framework for building native apps using React

Text #

Edit on GitHub

The most basic component in React Native is the Text component. The Text component simply renders text.

This example displays the string "Hello World!" on the device.

import React, { Component } from 'react'; +Text – React Native | A framework for building native apps using React

Text #

Edit on GitHub

The most basic component in React Native is the Text component. The Text component simply renders text.

This example displays the string "Hello World!" on the device.

import React, { Component } from 'react'; import { AppRegistry, Text } from 'react-native'; class TextBasics extends Component { diff --git a/releases/next/docs/basics-component-textinput.html b/releases/next/docs/basics-component-textinput.html index 13a3a2b75ee..66e597dd9a4 100644 --- a/releases/next/docs/basics-component-textinput.html +++ b/releases/next/docs/basics-component-textinput.html @@ -1,4 +1,4 @@ -TextInput – React Native | A framework for building native apps using React

TextInput #

Edit on GitHub

Direct text-based user input is a foundation for many apps. Writing a post or comment on a page is a canonical example of this. TextInput is a basic component that allows the user to enter text.

This example creates a simple TextInput box with the string Type something here as the placeholder when the TextInput is empty.

import React, { Component } from 'react'; +TextInput – React Native | A framework for building native apps using React

TextInput #

Edit on GitHub

Direct text-based user input is a foundation for many apps. Writing a post or comment on a page is a canonical example of this. TextInput is a basic component that allows the user to enter text.

This example creates a simple TextInput box with the string Type something here as the placeholder when the TextInput is empty.

import React, { Component } from 'react'; import { AppRegistry, Text, TextInput, View } from 'react-native'; class TextInputBasics extends Component { diff --git a/releases/next/docs/basics-component-view.html b/releases/next/docs/basics-component-view.html index 1fabbf99859..90af45ff61d 100644 --- a/releases/next/docs/basics-component-view.html +++ b/releases/next/docs/basics-component-view.html @@ -1,4 +1,4 @@ -View – React Native | A framework for building native apps using React

View #

Edit on GitHub

A View is the most basic building block for a React Native application. The View is an abstraction on top of the target platform's native equivalent, such as iOS's UIView.

A View is analogous to using a <div> HTML tag for building websites.

It is recommended that you wrap your components in a View to style and control layout.

The example below creates a View that aligns the string Hello in the top center of the device, something which could not be done with a Text component alone (i.e., a Text component without a View would place the string in a fixed location in the upper corner):

import React, { Component } from 'react'; +View – React Native | A framework for building native apps using React

View #

Edit on GitHub

A View is the most basic building block for a React Native application. The View is an abstraction on top of the target platform's native equivalent, such as iOS's UIView.

A View is analogous to using a <div> HTML tag for building websites.

It is recommended that you wrap your components in a View to style and control layout.

The example below creates a View that aligns the string Hello in the top center of the device, something which could not be done with a Text component alone (i.e., a Text component without a View would place the string in a fixed location in the upper corner):

import React, { Component } from 'react'; import { AppRegistry, Text, View } from 'react-native'; class ViewBasics extends Component { diff --git a/releases/next/docs/basics-components.html b/releases/next/docs/basics-components.html index 8e6b73ed157..58382bc9008 100644 --- a/releases/next/docs/basics-components.html +++ b/releases/next/docs/basics-components.html @@ -1,4 +1,4 @@ -Components – React Native | A framework for building native apps using React

Components #

Edit on GitHub

Components are the building blocks for a React Native application. A React Native user interface (UI) is specified by declaring components, often nested. Those components are then mapped to the native UI on the targeted platform.

Props #

this.props #

Components can be configured by passing properties props to the constructor. You can access props from your component's methods by accessing this.props. You should not alter your props within component methods.

State #

this.state #

Components maintain their state using the state object. You can access your component state via this.state. Each component should manage its own state. Parent components should not manage children state and children components should not manage parent component state.

this.setState({key: value, ...}) #

To update or change the state of your component passing a new object representing your newly desired state to this.setState(obj). The specificed keys will be merged into this.state. Any existing keys will be overridden by new values.

Core Components. #

React Native has a number of core components that are commonly used in applications, either on their own or combined to build new components.

© 2016 Facebook Inc.

Components #

Edit on GitHub

Components are the building blocks for a React Native application. A React Native user interface (UI) is specified by declaring components, often nested. Those components are then mapped to the native UI on the targeted platform.

Props #

this.props #

Components can be configured by passing properties props to the constructor. You can access props from your component's methods by accessing this.props. You should not alter your props within component methods.

State #

this.state #

Components maintain their state using the state object. You can access your component state via this.state. Each component should manage its own state. Parent components should not manage children state and children components should not manage parent component state.

this.setState({key: value, ...}) #

To update or change the state of your component passing a new object representing your newly desired state to this.setState(obj). The specificed keys will be merged into this.state. Any existing keys will be overridden by new values.

Core Components. #

React Native has a number of core components that are commonly used in applications, either on their own or combined to build new components.

© 2016 Facebook Inc.

Dimensions #

Edit on GitHub

A component's dimensions determine its size on the screen.

Fixed Dimensions #

The simplest way to set the dimensions of a component is by adding a fixed width and height to style. All dimensions in React Native are unitless, and represent density-independent pixels.

import React, { Component } from 'react'; +Dimensions – React Native | A framework for building native apps using React

Dimensions #

Edit on GitHub

A component's dimensions determine its size on the screen.

Fixed Dimensions #

The simplest way to set the dimensions of a component is by adding a fixed width and height to style. All dimensions in React Native are unitless, and represent density-independent pixels.

import React, { Component } from 'react'; import { AppRegistry, View } from 'react-native'; class FixedDimensionsBasics extends Component { diff --git a/releases/next/docs/basics-layout.html b/releases/next/docs/basics-layout.html deleted file mode 100644 index 2bd2ab3399d..00000000000 --- a/releases/next/docs/basics-layout.html +++ /dev/null @@ -1,79 +0,0 @@ -Layout – React Native | A framework for building native apps using React

Layout #

Edit on GitHub

A component can specify the layout of its children using the flexbox algorithm. Flexbox is designed to provide a consistent layout on different screen sizes.

You will normally use a combination of flexDirection, alignItems, and justifyContent to achieve the right layout.

Flexbox works the same way in React Native as it does in CSS on the web, with a few exceptions. The most notable one: the defaults are different, with flexDirection defaulting to column instead of row, and alignItems defaulting to stretch instead of flex-start.

Flex Direction #

Adding flexDirection to a component's style determines the primary axis of its layout. Should the children be organized horizontally (row) or vertically (column)? The default is column.

import React, { Component } from 'react'; -import { AppRegistry, View } from 'react-native'; - -class FlexDirectionBasics extends Component { - render() { - return ( - // Try setting `flexDirection` to `column`. - <View style={{flex: 1, flexDirection: 'row'}}> - <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} /> - <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} /> - <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} /> - </View> - ); - } -}; - -AppRegistry.registerComponent('AwesomeProject', () => FlexDirectionBasics);

Justify Content #

Adding justifyContent to a component's style determines the distribution of children along the primary axis. Should children be distributed at the start, the center, the end, or spaced evenly? Available options are flex-start, center, flex-end, space-around, and space-between.

import React, { Component } from 'react'; -import { AppRegistry, View } from 'react-native'; - -class JustifyContentBasics extends Component { - render() { - return ( - // Try setting `justifyContent` to `center`. - // Try setting `flexDirection` to `row`. - <View style={{ - flex: 1, - flexDirection: 'column', - justifyContent: 'space-between', - }}> - <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} /> - <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} /> - <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} /> - </View> - ); - } -}; - -AppRegistry.registerComponent('AwesomeProject', () => JustifyContentBasics);

Align Items #

Adding alignItems to a component's style determines the alignment of children along the secondary axis (if the primary axis is row, then the secondary is column, and vice versa). Should children be aligned at the start, the center, the end, or stretched to fill? Available options are flex-start, center, flex-end, and stretch.

For stretch to have an effect, children must not have a fixed dimension along the secondary axis. In the following example, setting alignItems: stretch does nothing until the width: 50 is removed from the children.

import React, { Component } from 'react'; -import { AppRegistry, View } from 'react-native'; - -class AlignItemsBasics { - render() { - return ( - // Try setting `alignItems` to 'flex-start' - // Try setting `justifyContent` to `flex-end`. - // Try setting `flexDirection` to `row`. - <View style={{ - flex: 1, - flexDirection: 'column', - justifyContent: 'center', - alignItems: 'center', - }}> - <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} /> - <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} /> - <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} /> - </View> - ); - } -}; - -AppRegistry.registerComponent('AwesomeProject', () => AlignItemsBasics);

API Reference #

We've covered the basics, but there are many other styles you may need for layouts. The full list is available here.

© 2016 Facebook Inc.
\ No newline at end of file diff --git a/releases/next/docs/cameraroll.html b/releases/next/docs/cameraroll.html index 4a6eb75ebb6..d045b0fa61d 100644 --- a/releases/next/docs/cameraroll.html +++ b/releases/next/docs/cameraroll.html @@ -1,4 +1,4 @@ -CameraRoll – React Native | A framework for building native apps using React

CameraRoll #

Edit on GitHub

CameraRoll provides access to the local camera roll / gallery.

Methods #

static saveImageWithTag(tag) #

static saveToCameraRoll(tag, type?) #

Saves the photo or video to the camera roll / gallery.

On Android, the tag must be a local image or video URI, such as "file:///sdcard/img.png".

On iOS, the tag can be any image URI (including local, remote asset-library and base64 data URIs) +CameraRoll – React Native | A framework for building native apps using React

CameraRoll #

Edit on GitHub

CameraRoll provides access to the local camera roll / gallery.

Methods #

static saveImageWithTag(tag) #

static saveToCameraRoll(tag, type?) #

Saves the photo or video to the camera roll / gallery.

On Android, the tag must be a local image or video URI, such as "file:///sdcard/img.png".

On iOS, the tag can be any image URI (including local, remote asset-library and base64 data URIs) or a local video file URI (remote or data URIs are not supported for saving video at this time).

If the tag has a file extension of .mov or .mp4, it will be inferred as a video. Otherwise it will be treated as a photo. To override the automatic choice, you can pass an optional type parameter that must be one of 'photo' or 'video'.

Returns a Promise which will resolve with the new URI.

static getPhotos(params) #

Returns a Promise with photo identifier objects from the local camera diff --git a/releases/next/docs/clipboard.html b/releases/next/docs/clipboard.html index 55516fa5013..b22a9d9621c 100644 --- a/releases/next/docs/clipboard.html +++ b/releases/next/docs/clipboard.html @@ -1,4 +1,4 @@ -Clipboard – React Native | A framework for building native apps using React

Clipboard #

Edit on GitHub

Clipboard gives you an interface for setting and getting content from Clipboard on both iOS and Android

Methods #

static getString() #

Get content of string type, this method returns a Promise, so you can use following code to get clipboard content

async _getContent() { +Clipboard – React Native | A framework for building native apps using React

Clipboard #

Edit on GitHub

Clipboard gives you an interface for setting and getting content from Clipboard on both iOS and Android

Methods #

static getString(0) #

Get content of string type, this method returns a Promise, so you can use following code to get clipboard content

async _getContent() { var content = await Clipboard.getString(); }

static setString(content) #

Set content of string type. You can use following code to set clipboard content

_setContent() { Clipboard.setString('hello world'); diff --git a/releases/next/docs/colors.html b/releases/next/docs/colors.html index d07c99232af..9f3f3027f70 100644 --- a/releases/next/docs/colors.html +++ b/releases/next/docs/colors.html @@ -1,4 +1,4 @@ -Colors – React Native | A framework for building native apps using React

Colors #

Edit on GitHub

The following formats are supported:

  • '#f0f' (#rgb)
  • '#f0fc' (#rgba)
  • '#ff00ff' (#rrggbb)
  • '#ff00ff00' (#rrggbbaa)
  • 'rgb(255, 255, 255)'
  • 'rgba(255, 255, 255, 1.0)'
  • 'hsl(360, 100%, 100%)'
  • 'hsla(360, 100%, 100%, 1.0)'
  • 'transparent'
  • 'red'
  • 0xff00ff00 (0xrrggbbaa)

For the named colors, React Native follows the CSS3 specification:

  • aliceblue (#f0f8ff)
  • antiquewhite (#faebd7)
  • aqua (#00ffff)
  • aquamarine (#7fffd4)
  • azure (#f0ffff)
  • beige (#f5f5dc)
  • bisque (#ffe4c4)
  • black (#000000)
  • blanchedalmond (#ffebcd)
  • blue (#0000ff)
  • blueviolet (#8a2be2)
  • brown (#a52a2a)
  • burlywood (#deb887)
  • cadetblue (#5f9ea0)
  • chartreuse (#7fff00)
  • chocolate (#d2691e)
  • coral (#ff7f50)
  • cornflowerblue (#6495ed)
  • cornsilk (#fff8dc)
  • crimson (#dc143c)
  • cyan (#00ffff)
  • darkblue (#00008b)
  • darkcyan (#008b8b)
  • darkgoldenrod (#b8860b)
  • darkgray (#a9a9a9)
  • darkgreen (#006400)
  • darkgrey (#a9a9a9)
  • darkkhaki (#bdb76b)
  • darkmagenta (#8b008b)
  • darkolivegreen (#556b2f)
  • darkorange (#ff8c00)
  • darkorchid (#9932cc)
  • darkred (#8b0000)
  • darksalmon (#e9967a)
  • darkseagreen (#8fbc8f)
  • darkslateblue (#483d8b)
  • darkslategray (#2f4f4f)
  • darkslategrey (#2f4f4f)
  • darkturquoise (#00ced1)
  • darkviolet (#9400d3)
  • deeppink (#ff1493)
  • deepskyblue (#00bfff)
  • dimgray (#696969)
  • dimgrey (#696969)
  • dodgerblue (#1e90ff)
  • firebrick (#b22222)
  • floralwhite (#fffaf0)
  • forestgreen (#228b22)
  • fuchsia (#ff00ff)
  • gainsboro (#dcdcdc)
  • ghostwhite (#f8f8ff)
  • gold (#ffd700)
  • goldenrod (#daa520)
  • gray (#808080)
  • green (#008000)
  • greenyellow (#adff2f)
  • grey (#808080)
  • honeydew (#f0fff0)
  • hotpink (#ff69b4)
  • indianred (#cd5c5c)
  • indigo (#4b0082)
  • ivory (#fffff0)
  • khaki (#f0e68c)
  • lavender (#e6e6fa)
  • lavenderblush (#fff0f5)
  • lawngreen (#7cfc00)
  • lemonchiffon (#fffacd)
  • lightblue (#add8e6)
  • lightcoral (#f08080)
  • lightcyan (#e0ffff)
  • lightgoldenrodyellow (#fafad2)
  • lightgray (#d3d3d3)
  • lightgreen (#90ee90)
  • lightgrey (#d3d3d3)
  • lightpink (#ffb6c1)
  • lightsalmon (#ffa07a)
  • lightseagreen (#20b2aa)
  • lightskyblue (#87cefa)
  • lightslategray (#778899)
  • lightslategrey (#778899)
  • lightsteelblue (#b0c4de)
  • lightyellow (#ffffe0)
  • lime (#00ff00)
  • limegreen (#32cd32)
  • linen (#faf0e6)
  • magenta (#ff00ff)
  • maroon (#800000)
  • mediumaquamarine (#66cdaa)
  • mediumblue (#0000cd)
  • mediumorchid (#ba55d3)
  • mediumpurple (#9370db)
  • mediumseagreen (#3cb371)
  • mediumslateblue (#7b68ee)
  • mediumspringgreen (#00fa9a)
  • mediumturquoise (#48d1cc)
  • mediumvioletred (#c71585)
  • midnightblue (#191970)
  • mintcream (#f5fffa)
  • mistyrose (#ffe4e1)
  • moccasin (#ffe4b5)
  • navajowhite (#ffdead)
  • navy (#000080)
  • oldlace (#fdf5e6)
  • olive (#808000)
  • olivedrab (#6b8e23)
  • orange (#ffa500)
  • orangered (#ff4500)
  • orchid (#da70d6)
  • palegoldenrod (#eee8aa)
  • palegreen (#98fb98)
  • paleturquoise (#afeeee)
  • palevioletred (#db7093)
  • papayawhip (#ffefd5)
  • peachpuff (#ffdab9)
  • peru (#cd853f)
  • pink (#ffc0cb)
  • plum (#dda0dd)
  • powderblue (#b0e0e6)
  • purple (#800080)
  • rebeccapurple (#663399)
  • red (#ff0000)
  • rosybrown (#bc8f8f)
  • royalblue (#4169e1)
  • saddlebrown (#8b4513)
  • salmon (#fa8072)
  • sandybrown (#f4a460)
  • seagreen (#2e8b57)
  • seashell (#fff5ee)
  • sienna (#a0522d)
  • silver (#c0c0c0)
  • skyblue (#87ceeb)
  • slateblue (#6a5acd)
  • slategray (#708090)
  • slategrey (#708090)
  • snow (#fffafa)
  • springgreen (#00ff7f)
  • steelblue (#4682b4)
  • tan (#d2b48c)
  • teal (#008080)
  • thistle (#d8bfd8)
  • tomato (#ff6347)
  • turquoise (#40e0d0)
  • violet (#ee82ee)
  • wheat (#f5deb3)
  • white (#ffffff)
  • whitesmoke (#f5f5f5)
  • yellow (#ffff00)
  • yellowgreen (#9acd32)
© 2016 Facebook Inc.

Colors #

Edit on GitHub

The following formats are supported:

  • '#f0f' (#rgb)
  • '#f0fc' (#rgba)
  • '#ff00ff' (#rrggbb)
  • '#ff00ff00' (#rrggbbaa)
  • 'rgb(255, 255, 255)'
  • 'rgba(255, 255, 255, 1.0)'
  • 'hsl(360, 100%, 100%)'
  • 'hsla(360, 100%, 100%, 1.0)'
  • 'transparent'
  • 'red'
  • 0xff00ff00 (0xrrggbbaa)

For the named colors, React Native follows the CSS3 specification:

  • aliceblue (#f0f8ff)
  • antiquewhite (#faebd7)
  • aqua (#00ffff)
  • aquamarine (#7fffd4)
  • azure (#f0ffff)
  • beige (#f5f5dc)
  • bisque (#ffe4c4)
  • black (#000000)
  • blanchedalmond (#ffebcd)
  • blue (#0000ff)
  • blueviolet (#8a2be2)
  • brown (#a52a2a)
  • burlywood (#deb887)
  • cadetblue (#5f9ea0)
  • chartreuse (#7fff00)
  • chocolate (#d2691e)
  • coral (#ff7f50)
  • cornflowerblue (#6495ed)
  • cornsilk (#fff8dc)
  • crimson (#dc143c)
  • cyan (#00ffff)
  • darkblue (#00008b)
  • darkcyan (#008b8b)
  • darkgoldenrod (#b8860b)
  • darkgray (#a9a9a9)
  • darkgreen (#006400)
  • darkgrey (#a9a9a9)
  • darkkhaki (#bdb76b)
  • darkmagenta (#8b008b)
  • darkolivegreen (#556b2f)
  • darkorange (#ff8c00)
  • darkorchid (#9932cc)
  • darkred (#8b0000)
  • darksalmon (#e9967a)
  • darkseagreen (#8fbc8f)
  • darkslateblue (#483d8b)
  • darkslategray (#2f4f4f)
  • darkslategrey (#2f4f4f)
  • darkturquoise (#00ced1)
  • darkviolet (#9400d3)
  • deeppink (#ff1493)
  • deepskyblue (#00bfff)
  • dimgray (#696969)
  • dimgrey (#696969)
  • dodgerblue (#1e90ff)
  • firebrick (#b22222)
  • floralwhite (#fffaf0)
  • forestgreen (#228b22)
  • fuchsia (#ff00ff)
  • gainsboro (#dcdcdc)
  • ghostwhite (#f8f8ff)
  • gold (#ffd700)
  • goldenrod (#daa520)
  • gray (#808080)
  • green (#008000)
  • greenyellow (#adff2f)
  • grey (#808080)
  • honeydew (#f0fff0)
  • hotpink (#ff69b4)
  • indianred (#cd5c5c)
  • indigo (#4b0082)
  • ivory (#fffff0)
  • khaki (#f0e68c)
  • lavender (#e6e6fa)
  • lavenderblush (#fff0f5)
  • lawngreen (#7cfc00)
  • lemonchiffon (#fffacd)
  • lightblue (#add8e6)
  • lightcoral (#f08080)
  • lightcyan (#e0ffff)
  • lightgoldenrodyellow (#fafad2)
  • lightgray (#d3d3d3)
  • lightgreen (#90ee90)
  • lightgrey (#d3d3d3)
  • lightpink (#ffb6c1)
  • lightsalmon (#ffa07a)
  • lightseagreen (#20b2aa)
  • lightskyblue (#87cefa)
  • lightslategray (#778899)
  • lightslategrey (#778899)
  • lightsteelblue (#b0c4de)
  • lightyellow (#ffffe0)
  • lime (#00ff00)
  • limegreen (#32cd32)
  • linen (#faf0e6)
  • magenta (#ff00ff)
  • maroon (#800000)
  • mediumaquamarine (#66cdaa)
  • mediumblue (#0000cd)
  • mediumorchid (#ba55d3)
  • mediumpurple (#9370db)
  • mediumseagreen (#3cb371)
  • mediumslateblue (#7b68ee)
  • mediumspringgreen (#00fa9a)
  • mediumturquoise (#48d1cc)
  • mediumvioletred (#c71585)
  • midnightblue (#191970)
  • mintcream (#f5fffa)
  • mistyrose (#ffe4e1)
  • moccasin (#ffe4b5)
  • navajowhite (#ffdead)
  • navy (#000080)
  • oldlace (#fdf5e6)
  • olive (#808000)
  • olivedrab (#6b8e23)
  • orange (#ffa500)
  • orangered (#ff4500)
  • orchid (#da70d6)
  • palegoldenrod (#eee8aa)
  • palegreen (#98fb98)
  • paleturquoise (#afeeee)
  • palevioletred (#db7093)
  • papayawhip (#ffefd5)
  • peachpuff (#ffdab9)
  • peru (#cd853f)
  • pink (#ffc0cb)
  • plum (#dda0dd)
  • powderblue (#b0e0e6)
  • purple (#800080)
  • rebeccapurple (#663399)
  • red (#ff0000)
  • rosybrown (#bc8f8f)
  • royalblue (#4169e1)
  • saddlebrown (#8b4513)
  • salmon (#fa8072)
  • sandybrown (#f4a460)
  • seagreen (#2e8b57)
  • seashell (#fff5ee)
  • sienna (#a0522d)
  • silver (#c0c0c0)
  • skyblue (#87ceeb)
  • slateblue (#6a5acd)
  • slategray (#708090)
  • slategrey (#708090)
  • snow (#fffafa)
  • springgreen (#00ff7f)
  • steelblue (#4682b4)
  • tan (#d2b48c)
  • teal (#008080)
  • thistle (#d8bfd8)
  • tomato (#ff6347)
  • turquoise (#40e0d0)
  • violet (#ee82ee)
  • wheat (#f5deb3)
  • white (#ffffff)
  • whitesmoke (#f5f5f5)
  • yellow (#ffff00)
  • yellowgreen (#9acd32)
© 2016 Facebook Inc.

Communication between native and React Native #

Edit on GitHub

In Integrating with Existing Apps guide and Native UI Components guide we learn how to embed React Native in a native component and vice versa. When we mix native and React Native components, we'll eventually find a need to communicate between these two worlds. Some ways to achieve that have been already mentioned in other guides. This article summarizes available techniques.

Introduction #

React Native is inspired by React, so the basic idea of the information flow is similar. The flow in React is one-directional. We maintain a hierarchy of components, in which each component depends only on its parent and own internal state. We do this with properties: data is passed from a parent to its children in a top-down manner. If we have an ancestor component that rely on the state of its descendant, the recommended solution would be to pass down a callback that would be used by the descendant to update the ancestor.

The same concept applies to React Native. As long as we are building our application purely within the framework, we can drive our app with properties and callbacks. But, when we mix React Native and native components, we need some special, cross-language mechanisms that would allow us to pass information between them.

Properties #

Properties are the simplest way of cross-component communication. So we need a way to pass properties both from native to React Native, and from React Native to native.

Passing properties from native to React Native #

In order to embed a React Native view in a native component, we use RCTRootView. RCTRootView is a UIView that holds a React Native app. It also provides an interface between native side and the hosted app.

RCTRootView has an initializer that allows you to pass arbitrary properties down to the React Native app. The initialProperties parameter has to be an instance of NSDictionary. The dictionary is internally converted into a JSON object that the top-level JS component can reference.

NSArray *imageList = @[@"http://foo.com/bar1.png", +Communication between native and React Native – React Native | A framework for building native apps using React

Communication between native and React Native #

Edit on GitHub

In Integrating with Existing Apps guide and Native UI Components guide we learn how to embed React Native in a native component and vice versa. When we mix native and React Native components, we'll eventually find a need to communicate between these two worlds. Some ways to achieve that have been already mentioned in other guides. This article summarizes available techniques.

Introduction #

React Native is inspired by React, so the basic idea of the information flow is similar. The flow in React is one-directional. We maintain a hierarchy of components, in which each component depends only on its parent and own internal state. We do this with properties: data is passed from a parent to its children in a top-down manner. If we have an ancestor component that rely on the state of its descendant, the recommended solution would be to pass down a callback that would be used by the descendant to update the ancestor.

The same concept applies to React Native. As long as we are building our application purely within the framework, we can drive our app with properties and callbacks. But, when we mix React Native and native components, we need some special, cross-language mechanisms that would allow us to pass information between them.

Properties #

Properties are the simplest way of cross-component communication. So we need a way to pass properties both from native to React Native, and from React Native to native.

Passing properties from native to React Native #

In order to embed a React Native view in a native component, we use RCTRootView. RCTRootView is a UIView that holds a React Native app. It also provides an interface between native side and the hosted app.

RCTRootView has an initializer that allows you to pass arbitrary properties down to the React Native app. The initialProperties parameter has to be an instance of NSDictionary. The dictionary is internally converted into a JSON object that the top-level JS component can reference.

NSArray *imageList = @[@"http://foo.com/bar1.png", @"http://foo.com/bar2.png"]; NSDictionary *props = @{@"images" : imageList}; diff --git a/releases/next/docs/datepickerandroid.html b/releases/next/docs/datepickerandroid.html index 10f98372c81..5bbc76bed14 100644 --- a/releases/next/docs/datepickerandroid.html +++ b/releases/next/docs/datepickerandroid.html @@ -1,4 +1,4 @@ -DatePickerAndroid – React Native | A framework for building native apps using React

DatePickerAndroid #

Edit on GitHub

Opens the standard Android date picker dialog.

Example #

try { +DatePickerAndroid – React Native | A framework for building native apps using React

DatePickerAndroid #

Edit on GitHub

Opens the standard Android date picker dialog.

Example #

try { const {action, year, month, day} = await DatePickerAndroid.open({ // Use `new Date()` for current date. // May 25 2020. Month 0 is January. @@ -16,7 +16,7 @@ day if the user picked a date. If the user dismissed the dialog, the Promise will still be resolved with action being DatePickerAndroid.dismissedAction and all the other keys being undefined. Always check whether the action before reading the values.

Note the native date picker dialog has some UI glitches on Android 4 and lower -when using the minDate and maxDate options.

static dateSetAction() #

A date has been selected.

static dismissedAction() #

The dialog has been dismissed.

Examples #

Edit on GitHub
'use strict'; +when using the minDate and maxDate options.

static dateSetAction(0) #

A date has been selected.

static dismissedAction(0) #

The dialog has been dismissed.

Examples #

Edit on GitHub
'use strict'; var React = require('react'); var ReactNative = require('react-native'); diff --git a/releases/next/docs/datepickerios.html b/releases/next/docs/datepickerios.html index ad1345b8144..92afb66eed2 100644 --- a/releases/next/docs/datepickerios.html +++ b/releases/next/docs/datepickerios.html @@ -1,4 +1,4 @@ -DatePickerIOS – React Native | A framework for building native apps using React

DatePickerIOS #

Edit on GitHub

Use DatePickerIOS to render a date/time picker (selector) on iOS. This is +DatePickerIOS – React Native | A framework for building native apps using React

DatePickerIOS #

Edit on GitHub

Use DatePickerIOS to render a date/time picker (selector) on iOS. This is a controlled component, so you must hook in to the onDateChange callback and update the date prop in order for the component to update, otherwise the user's change will be reverted immediately to reflect props.date as the diff --git a/releases/next/docs/debugging.html b/releases/next/docs/debugging.html index 3f9163ae257..e76f4ba328e 100644 --- a/releases/next/docs/debugging.html +++ b/releases/next/docs/debugging.html @@ -1,4 +1,4 @@ -Debugging – React Native | A framework for building native apps using React

Debugging #

Edit on GitHub

Accessing the In-App Developer Menu #

You can access the developer menu by shaking your device or by selecting "Shake Gesture" inside the Hardware menu in the iOS Simulator. You can also use the Command + D keyboard shortcut when your app is running in the iPhone Simulator, or Command + M when running in an Android emulator.

The Developer Menu is disabled in release (production) builds.

Reloading JavaScript #

Instead of recompiling your app every time you make a change, you can reload your app's JavaScript code instantly. To do so, select "Reload" from the Developer Menu. You can also press Command + R in the iOS Simulator, or press R twice on Android emulators.

If the Command + R keyboard shortcut does not seem to reload the iOS Simulator, go to the Hardware menu, select Keyboard, and make sure that "Connect Hardware Keyboard" is checked.

Automatic reloading #

You can speed up your development times by having your app reload automatically any time your code changes. Automatic reloading can be enabled by selecting "Enable Live Reload" from the Developer Menu.

You may even go a step further and keep your app running as new versions of your files are injected into the JavaScript bundle automatically by enabling Hot Reloading from the Developer Menu. This will allow you to persist the app's state through reloads.

There are some instances where hot reloading cannot be implemented perfectly. If you run into any issues, use a full reload to reset your app.

You will need to rebuild your app for changes to take effect in certain situations:

  • You have added new resources to your native app's bundle, such as an image in Images.xcassets on iOS or the res/drawable folder on Android.
  • You have modified native code (Objective-C/Swift on iOS or Java/C++ on Android).

In-app Errors and Warnings #

Errors and warnings are displayed inside your app in development builds.

Errors #

In-app errors are displayed in a full screen alert with a red background inside your app. This screen is known as a RedBox. You can use console.error() to manually trigger one.

Warnings #

Warnings will be displayed on screen with a yellow background. These alerts are known as YellowBoxes. Click on the alerts to show more information or to dismiss them.

As with a RedBox, you can use console.warn() to trigger a YellowBox.

YellowBoxes can be disabled during development by using console.disableYellowBox = true;. Specific warnings can be ignored programmatically by setting an array of prefixes that should be ignored: console.ignoredYellowBox = ['Warning: ...'];

RedBoxes and YellowBoxes are automatically disabled in release (production) builds.

Accessing console logs #

You can display the console logs for an iOS or Android app by using the following commands in a terminal while the app is running:

$ react-native log-ios +Debugging – React Native | A framework for building native apps using React

Debugging #

Edit on GitHub

Accessing the In-App Developer Menu #

You can access the developer menu by shaking your device or by selecting "Shake Gesture" inside the Hardware menu in the iOS Simulator. You can also use the Command + D keyboard shortcut when your app is running in the iPhone Simulator, or Command + M when running in an Android emulator.

The Developer Menu is disabled in release (production) builds.

Reloading JavaScript #

Instead of recompiling your app every time you make a change, you can reload your app's JavaScript code instantly. To do so, select "Reload" from the Developer Menu. You can also press Command + R in the iOS Simulator, or press R twice on Android emulators.

If the Command + R keyboard shortcut does not seem to reload the iOS Simulator, go to the Hardware menu, select Keyboard, and make sure that "Connect Hardware Keyboard" is checked.

Automatic reloading #

You can speed up your development times by having your app reload automatically any time your code changes. Automatic reloading can be enabled by selecting "Enable Live Reload" from the Developer Menu.

You may even go a step further and keep your app running as new versions of your files are injected into the JavaScript bundle automatically by enabling Hot Reloading from the Developer Menu. This will allow you to persist the app's state through reloads.

There are some instances where hot reloading cannot be implemented perfectly. If you run into any issues, use a full reload to reset your app.

You will need to rebuild your app for changes to take effect in certain situations:

  • You have added new resources to your native app's bundle, such as an image in Images.xcassets on iOS or the res/drawable folder on Android.
  • You have modified native code (Objective-C/Swift on iOS or Java/C++ on Android).

In-app Errors and Warnings #

Errors and warnings are displayed inside your app in development builds.

Errors #

In-app errors are displayed in a full screen alert with a red background inside your app. This screen is known as a RedBox. You can use console.error() to manually trigger one.

Warnings #

Warnings will be displayed on screen with a yellow background. These alerts are known as YellowBoxes. Click on the alerts to show more information or to dismiss them.

As with a RedBox, you can use console.warn() to trigger a YellowBox.

YellowBoxes can be disabled during development by using console.disableYellowBox = true;. Specific warnings can be ignored programmatically by setting an array of prefixes that should be ignored: console.ignoredYellowBox = ['Warning: ...'];

RedBoxes and YellowBoxes are automatically disabled in release (production) builds.

Accessing console logs #

You can display the console logs for an iOS or Android app by using the following commands in a terminal while the app is running:

$ react-native log-ios $ react-native log-android

You may also access these through Debug → Open System Log... in the iOS Simulator or by running adb logcat *:S ReactNative:V ReactNativeJS:V in a terminal while an Android app is running on a device or emulator.

Chrome Developer Tools #

To debug the JavaScript code in Chrome, select "Debug JS Remotely" from the Developer Menu. This will open a new tab at http://localhost:8081/debugger-ui.

Select Tools → Developer Tools from the Chrome Menu to open the Developer Tools. You may also access the DevTools using keyboard shortcuts (Command + Option + I on Mac, Ctrl + Shift + I on Windows). You may also want to enable Pause On Caught Exceptions for a better debugging experience.

It is currently not possible to use the "React" tab in the Chrome Developer Tools to inspect app widgets. You can use Nuclide's "React Native Inspector" as a workaround.

Debugging on a device with Chrome Developer Tools #

On iOS devices, open the file RCTWebSocketExecutor.m and change "localhost" to the IP address of your computer, then select "Debug JS Remotely" from the Developer Menu.

On Android 5.0+ devices connected via USB, you can use the adb command line tool to setup port forwarding from the device to your computer:

adb reverse tcp:8081 tcp:8081

Alternatively, select "Dev Settings" from the Developer Menu, then update the "Debug server host for device" setting to match the IP address of your computer.

If you run into any issues, it may be possible that one of your Chrome extensions is interacting in unexpected ways with the debugger. Try disabling all of your extensions and re-enabling them one-by-one until you find the problematic extension.

Debugging using a custom JavaScript debugger #

To use a custom JavaScript debugger in place of Chrome Developer Tools, set the REACT_DEBUGGER environment variable to a command that will start your custom debugger. You can then select "Debug JS Remotely" from the Developer Menu to start debugging.

The debugger will receive a list of all project roots, separated by a space. For example, if you set REACT_DEBUGGER="node /path/to/launchDebugger.js --port 2345 --type ReactNative", then the command node /path/to/launchDebugger.js --port 2345 --type ReactNative /path/to/reactNative/app will be used to start your debugger.

Custom debugger commands executed this way should be short-lived processes, and they shouldn't produce more than 200 kilobytes of output.

Performance Monitor #

You can enable a performance overlay to help you debug performance problems by selecting "Perf Monitor" in the Developer Menu.

© 2016 Facebook Inc.

Dimensions #

Edit on GitHub

Methods #

static set(dims) #

This should only be called from native code by sending the +Dimensions – React Native | A framework for building native apps using React

Dimensions #

Edit on GitHub

Methods #

static set(dims) #

This should only be called from native code by sending the didUpdateDimensions event.

@param {object} dims Simple string-keyed object of dimensions to set

static get(dim) #

Initial dimensions are set before runApplication is called so they should be available before any other require's are run, but may be updated later.

Note: Although dimensions are available immediately, they may change (e.g due to device rotation) so any rendering logic or styles that depend on diff --git a/releases/next/docs/direct-manipulation.html b/releases/next/docs/direct-manipulation.html index dbad740d550..597f7fe0ec4 100644 --- a/releases/next/docs/direct-manipulation.html +++ b/releases/next/docs/direct-manipulation.html @@ -1,4 +1,4 @@ -Direct Manipulation – React Native | A framework for building native apps using React

Direct Manipulation #

Edit on GitHub

It is sometimes necessary to make changes directly to a component +Direct Manipulation – React Native | A framework for building native apps using React

Direct Manipulation #

Edit on GitHub

It is sometimes necessary to make changes directly to a component without using state/props to trigger a re-render of the entire subtree. When using React in the browser for example, you sometimes need to directly modify a DOM node, and the same is true for views in mobile diff --git a/releases/next/docs/drawerlayoutandroid.html b/releases/next/docs/drawerlayoutandroid.html index c87d9e90ae4..a6eed565ec1 100644 --- a/releases/next/docs/drawerlayoutandroid.html +++ b/releases/next/docs/drawerlayoutandroid.html @@ -1,4 +1,4 @@ -DrawerLayoutAndroid – React Native | A framework for building native apps using React

DrawerLayoutAndroid #

Edit on GitHub

React component that wraps the platform DrawerLayout (Android only). The +DrawerLayoutAndroid – React Native | A framework for building native apps using React

DrawerLayoutAndroid #

Edit on GitHub

React component that wraps the platform DrawerLayout (Android only). The Drawer (typically used for navigation) is rendered with renderNavigationView and direct children are the main view (where your content goes). The navigation view is initially not visible on the screen, but can be pulled in from the @@ -37,7 +37,7 @@ from the edge of the window.

renderNavigationView function #

The navigation view that will be rendered to the side of the screen and can be pulled in.

statusBarBackgroundColor color #

Make the drawer take the entire screen and draw the background of the status bar to allow it to open over the status bar. It will only have an -effect on API 21+.

Methods #

openDrawer() #

Opens the drawer.

closeDrawer() #

Closes the drawer.

© 2016 Facebook Inc.

Flexbox #

Edit on GitHub

Props #

alignItems enum('flex-start', 'flex-end', 'center', 'stretch') #

alignSelf enum('auto', 'flex-start', 'flex-end', 'center', 'stretch') #

borderBottomWidth number #

borderLeftWidth number #

borderRightWidth number #

borderTopWidth number #

borderWidth number #

bottom number #

flex number #

flexDirection enum('row', 'row-reverse', 'column', 'column-reverse') #

flexWrap enum('wrap', 'nowrap') #

height number #

justifyContent enum('flex-start', 'flex-end', 'center', 'space-between', 'space-around') #

left number #

margin number #

marginBottom number #

marginHorizontal number #

marginLeft number #

marginRight number #

marginTop number #

marginVertical number #

maxHeight number #

maxWidth number #

minHeight number #

minWidth number #

padding number #

paddingBottom number #

paddingHorizontal number #

paddingLeft number #

paddingRight number #

paddingTop number #

paddingVertical number #

position enum('absolute', 'relative') #

right number #

top number #

width number #

zIndex number #

© 2016 Facebook Inc.

Layout with Flexbox #

Edit on GitHub

A component can specify the layout of its children using the flexbox algorithm. Flexbox is designed to provide a consistent layout on different screen sizes.

You will normally use a combination of flexDirection, alignItems, and justifyContent to achieve the right layout.

Flexbox works the same way in React Native as it does in CSS on the web, with a few exceptions. The defaults are different, with flexDirection defaulting to column instead of row, and alignItems defaulting to stretch instead of flex-start, and the flex parameter only supports a single number.

Flex Direction #

Adding flexDirection to a component's style determines the primary axis of its layout. Should the children be organized horizontally (row) or vertically (column)? The default is column.

import React, { Component } from 'react'; +import { AppRegistry, View } from 'react-native'; + +class FlexDirectionBasics extends Component { + render() { + return ( + // Try setting `flexDirection` to `column`. + <View style={{flex: 1, flexDirection: 'row'}}> + <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} /> + <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} /> + <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} /> + </View> + ); + } +}; + +AppRegistry.registerComponent('AwesomeProject', () => FlexDirectionBasics);

Justify Content #

Adding justifyContent to a component's style determines the distribution of children along the primary axis. Should children be distributed at the start, the center, the end, or spaced evenly? Available options are flex-start, center, flex-end, space-around, and space-between.

import React, { Component } from 'react'; +import { AppRegistry, View } from 'react-native'; + +class JustifyContentBasics extends Component { + render() { + return ( + // Try setting `justifyContent` to `center`. + // Try setting `flexDirection` to `row`. + <View style={{ + flex: 1, + flexDirection: 'column', + justifyContent: 'space-between', + }}> + <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} /> + <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} /> + <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} /> + </View> + ); + } +}; + +AppRegistry.registerComponent('AwesomeProject', () => JustifyContentBasics);

Align Items #

Adding alignItems to a component's style determines the alignment of children along the secondary axis (if the primary axis is row, then the secondary is column, and vice versa). Should children be aligned at the start, the center, the end, or stretched to fill? Available options are flex-start, center, flex-end, and stretch.

For stretch to have an effect, children must not have a fixed dimension along the secondary axis. In the following example, setting alignItems: stretch does nothing until the width: 50 is removed from the children.

import React, { Component } from 'react'; +import { AppRegistry, View } from 'react-native'; + +class AlignItemsBasics { + render() { + return ( + // Try setting `alignItems` to 'flex-start' + // Try setting `justifyContent` to `flex-end`. + // Try setting `flexDirection` to `row`. + <View style={{ + flex: 1, + flexDirection: 'column', + justifyContent: 'center', + alignItems: 'center', + }}> + <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} /> + <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} /> + <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} /> + </View> + ); + } +}; + +AppRegistry.registerComponent('AwesomeProject', () => AlignItemsBasics);

Going Deeper #

We've covered the basics, but there are many other styles you may need for layouts. The full list of props that control layout is documented here.

© 2016 Facebook Inc.

Geolocation #

Edit on GitHub

The Geolocation API follows the web spec: +Geolocation – React Native | A framework for building native apps using React

Geolocation #

Edit on GitHub

The Geolocation API follows the web spec: https://developer.mozilla.org/en-US/docs/Web/API/Geolocation

iOS #

You need to include the NSLocationWhenInUseUsageDescription key in Info.plist to enable geolocation. Geolocation is enabled by default when you create a project with react-native init.

Android #

To request access to location, you need to add the following line to your @@ -6,7 +6,7 @@ app's AndroidManifest.xml:

<uses-permission and options: timeout (ms), maximumAge (ms), enableHighAccuracy (bool) On Android, this can return almost immediately if the location is cached or request an update, which might take a while.

static watchPosition(success, error?, options?) #

Invokes the success callback whenever the location changes. Supported -options: timeout (ms), maximumAge (ms), enableHighAccuracy (bool), distanceFilter(m)

static clearWatch(watchID) #

static stopObserving() #

Examples #

Edit on GitHub
/* eslint no-console: 0 */ +options: timeout (ms), maximumAge (ms), enableHighAccuracy (bool), distanceFilter(m)

static clearWatch(watchID) #

static stopObserving(0) #

Examples #

Edit on GitHub
/* eslint no-console: 0 */ 'use strict'; diff --git a/releases/next/docs/gesture-responder-system.html b/releases/next/docs/gesture-responder-system.html index 521318f1a7c..f9cd59c9024 100644 --- a/releases/next/docs/gesture-responder-system.html +++ b/releases/next/docs/gesture-responder-system.html @@ -1,4 +1,4 @@ -Gesture Responder System – React Native | A framework for building native apps using React

Gesture Responder System #

Edit on GitHub

Gesture recognition on mobile devices is much more complicated than web. A touch can go through several phases as the app determines what the user's intention is. For example, the app needs to determine if the touch is scrolling, sliding on a widget, or tapping. This can even change during the duration of a touch. There can also be multiple simultaneous touches.

The touch responder system is needed to allow components to negotiate these touch interactions without any additional knowledge about their parent or child components. This system is implemented in ResponderEventPlugin.js, which contains further details and documentation.

Best Practices #

Users can feel huge differences in the usability of web apps vs. native, and this is one of the big causes. Every action should have the following attributes:

  • Feedback/highlighting- show the user what is handling their touch, and what will happen when they release the gesture
  • Cancel-ability- when making an action, the user should be able to abort it mid-touch by dragging their finger away

These features make users more comfortable while using an app, because it allows people to experiment and interact without fear of making mistakes.

TouchableHighlight and Touchable* #

The responder system can be complicated to use. So we have provided an abstract Touchable implementation for things that should be "tappable". This uses the responder system and allows you to easily configure tap interactions declaratively. Use TouchableHighlight anywhere where you would use a button or link on web.

Responder Lifecycle #

A view can become the touch responder by implementing the correct negotiation methods. There are two methods to ask the view if it wants to become responder:

  • View.props.onStartShouldSetResponder: (evt) => true, - Does this view want to become responder on the start of a touch?
  • View.props.onMoveShouldSetResponder: (evt) => true, - Called for every touch move on the View when it is not the responder: does this view want to "claim" touch responsiveness?

If the View returns true and attempts to become the responder, one of the following will happen:

  • View.props.onResponderGrant: (evt) => {} - The View is now responding for touch events. This is the time to highlight and show the user what is happening
  • View.props.onResponderReject: (evt) => {} - Something else is the responder right now and will not release it

If the view is responding, the following handlers can be called:

  • View.props.onResponderMove: (evt) => {} - The user is moving their finger
  • View.props.onResponderRelease: (evt) => {} - Fired at the end of the touch, ie "touchUp"
  • View.props.onResponderTerminationRequest: (evt) => true - Something else wants to become responder. Should this view release the responder? Returning true allows release
  • View.props.onResponderTerminate: (evt) => {} - The responder has been taken from the View. Might be taken by other views after a call to onResponderTerminationRequest, or might be taken by the OS without asking (happens with control center/ notification center on iOS)

evt is a synthetic touch event with the following form:

  • nativeEvent
    • changedTouches - Array of all touch events that have changed since the last event
    • identifier - The ID of the touch
    • locationX - The X position of the touch, relative to the element
    • locationY - The Y position of the touch, relative to the element
    • pageX - The X position of the touch, relative to the root element
    • pageY - The Y position of the touch, relative to the root element
    • target - The node id of the element receiving the touch event
    • timestamp - A time identifier for the touch, useful for velocity calculation
    • touches - Array of all current touches on the screen

Capture ShouldSet Handlers #

onStartShouldSetResponder and onMoveShouldSetResponder are called with a bubbling pattern, where the deepest node is called first. That means that the deepest component will become responder when multiple Views return true for *ShouldSetResponder handlers. This is desirable in most cases, because it makes sure all controls and buttons are usable.

However, sometimes a parent will want to make sure that it becomes responder. This can be handled by using the capture phase. Before the responder system bubbles up from the deepest component, it will do a capture phase, firing on*ShouldSetResponderCapture. So if a parent View wants to prevent the child from becoming responder on a touch start, it should have a onStartShouldSetResponderCapture handler which returns true.

  • View.props.onStartShouldSetResponderCapture: (evt) => true,
  • View.props.onMoveShouldSetResponderCapture: (evt) => true,

PanResponder #

For higher-level gesture interpretation, check out PanResponder.

© 2016 Facebook Inc.

Gesture Responder System #

Edit on GitHub

Gesture recognition on mobile devices is much more complicated than web. A touch can go through several phases as the app determines what the user's intention is. For example, the app needs to determine if the touch is scrolling, sliding on a widget, or tapping. This can even change during the duration of a touch. There can also be multiple simultaneous touches.

The touch responder system is needed to allow components to negotiate these touch interactions without any additional knowledge about their parent or child components. This system is implemented in ResponderEventPlugin.js, which contains further details and documentation.

Best Practices #

Users can feel huge differences in the usability of web apps vs. native, and this is one of the big causes. Every action should have the following attributes:

  • Feedback/highlighting- show the user what is handling their touch, and what will happen when they release the gesture
  • Cancel-ability- when making an action, the user should be able to abort it mid-touch by dragging their finger away

These features make users more comfortable while using an app, because it allows people to experiment and interact without fear of making mistakes.

TouchableHighlight and Touchable* #

The responder system can be complicated to use. So we have provided an abstract Touchable implementation for things that should be "tappable". This uses the responder system and allows you to easily configure tap interactions declaratively. Use TouchableHighlight anywhere where you would use a button or link on web.

Responder Lifecycle #

A view can become the touch responder by implementing the correct negotiation methods. There are two methods to ask the view if it wants to become responder:

  • View.props.onStartShouldSetResponder: (evt) => true, - Does this view want to become responder on the start of a touch?
  • View.props.onMoveShouldSetResponder: (evt) => true, - Called for every touch move on the View when it is not the responder: does this view want to "claim" touch responsiveness?

If the View returns true and attempts to become the responder, one of the following will happen:

  • View.props.onResponderGrant: (evt) => {} - The View is now responding for touch events. This is the time to highlight and show the user what is happening
  • View.props.onResponderReject: (evt) => {} - Something else is the responder right now and will not release it

If the view is responding, the following handlers can be called:

  • View.props.onResponderMove: (evt) => {} - The user is moving their finger
  • View.props.onResponderRelease: (evt) => {} - Fired at the end of the touch, ie "touchUp"
  • View.props.onResponderTerminationRequest: (evt) => true - Something else wants to become responder. Should this view release the responder? Returning true allows release
  • View.props.onResponderTerminate: (evt) => {} - The responder has been taken from the View. Might be taken by other views after a call to onResponderTerminationRequest, or might be taken by the OS without asking (happens with control center/ notification center on iOS)

evt is a synthetic touch event with the following form:

  • nativeEvent
    • changedTouches - Array of all touch events that have changed since the last event
    • identifier - The ID of the touch
    • locationX - The X position of the touch, relative to the element
    • locationY - The Y position of the touch, relative to the element
    • pageX - The X position of the touch, relative to the root element
    • pageY - The Y position of the touch, relative to the root element
    • target - The node id of the element receiving the touch event
    • timestamp - A time identifier for the touch, useful for velocity calculation
    • touches - Array of all current touches on the screen

Capture ShouldSet Handlers #

onStartShouldSetResponder and onMoveShouldSetResponder are called with a bubbling pattern, where the deepest node is called first. That means that the deepest component will become responder when multiple Views return true for *ShouldSetResponder handlers. This is desirable in most cases, because it makes sure all controls and buttons are usable.

However, sometimes a parent will want to make sure that it becomes responder. This can be handled by using the capture phase. Before the responder system bubbles up from the deepest component, it will do a capture phase, firing on*ShouldSetResponderCapture. So if a parent View wants to prevent the child from becoming responder on a touch start, it should have a onStartShouldSetResponderCapture handler which returns true.

  • View.props.onStartShouldSetResponderCapture: (evt) => true,
  • View.props.onMoveShouldSetResponderCapture: (evt) => true,

PanResponder #

For higher-level gesture interpretation, check out PanResponder.

© 2016 Facebook Inc.

Getting Started #

Edit on GitHub
+Getting Started – React Native | A framework for building native apps using React

Getting Started #

Edit on GitHub