diff --git a/releases/next/docs/accessibility.html b/releases/next/docs/accessibility.html index 9ae4fba364f..901feb36016 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 53283f25240..bf75ea3af45 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 dfc0f583ec5..e0f70d8b31d 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 e6b4d63ff01..3997d592aed 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 109d699ccd0..c4ce1ec2323 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

The AlertsIOS utility provides two functions: alert and prompt. All +AlertIOS – React Native | A framework for building native apps using React

AlertIOS #

Edit on GitHub

The AlertsIOS utility provides two functions: alert and prompt. All functionality available through AlertIOS.alert is also available in the cross-platform Alert.alert, which we recommend you use if you don't need iOS-specific functionality.

AlertIOS.prompt allows you to prompt the user for input inside of an diff --git a/releases/next/docs/android-building-from-source.html b/releases/next/docs/android-building-from-source.html index be5822550d3..748558131d7 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 a4e4d19b1cb..f7cd04c4c0d 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.

We are planning improvements to the React Native documentation. Your responses to this short survey will go a long way in helping us provide valuable content. Thank you!

Take Survey
© 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.

We are planning improvements to the React Native documentation. Your responses to this short survey will go a long way in helping us provide valuable content. Thank you!

Take Survey
© 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 diff --git a/releases/next/docs/animations.html b/releases/next/docs/animations.html index 67f6c37ba34..4aa90496cf9 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 29a02b3fc1e..426a1e6c00c 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 diff --git a/releases/next/docs/appstate.html b/releases/next/docs/appstate.html index 5ff56af94b7..6406693336f 100644 --- a/releases/next/docs/appstate.html +++ b/releases/next/docs/appstate.html @@ -1,4 +1,4 @@ -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, +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 diff --git a/releases/next/docs/asyncstorage.html b/releases/next/docs/asyncstorage.html index e659cc113ff..ddf86114d74 100644 --- a/releases/next/docs/asyncstorage.html +++ b/releases/next/docs/asyncstorage.html @@ -1,4 +1,4 @@ -AsyncStorage – React Native | A framework for building native apps using React

    AsyncStorage #

    Edit on GitHub

    AsyncStorage is a simple, asynchronous, persistent, key-value storage +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 diff --git a/releases/next/docs/backandroid.html b/releases/next/docs/backandroid.html index 16d67a58673..f4328b4f679 100644 --- a/releases/next/docs/backandroid.html +++ b/releases/next/docs/backandroid.html @@ -1,4 +1,4 @@ -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(); diff --git a/releases/next/docs/cameraroll.html b/releases/next/docs/cameraroll.html index 5027d9cf483..cb0243c7e1f 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 3a58b19ece5..2caf5e1864b 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() #

    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 6f3142c5e06..a00a4013b1b 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)

    We are planning improvements to the React Native documentation. Your responses to this short survey will go a long way in helping us provide valuable content. Thank you!

    Take Survey
    © 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)

    We are planning improvements to the React Native documentation. Your responses to this short survey will go a long way in helping us provide valuable content. Thank you!

    Take Survey
    © 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 46787295e9b..9477bf6f4a9 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. diff --git a/releases/next/docs/datepickerios.html b/releases/next/docs/datepickerios.html index 566e839bbf2..d71a1b3331d 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 5935b8a1f46..12e9263eef7 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

    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 the In-App Developer Menu #

    You can access the developer menu by shaking your device. 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 #

    Selecting Reload from the Developer Menu will reload the JavaScript that powers your application. You can also press Command⌘ + R in the iOS Simulator, or press R twice on Android emulators.

    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 in res/drawable folder on Android.
    • You have modified native code (Objective-C/Swift on iOS or Java/C++ on Android).

    Automatic reloading #

    You may enable Live Reload to automatically trigger a reload whenever your JavaScript code changes.

    Live Reload is available on iOS via the Developer Menu. On Android, select "Dev Settings" from the Developer Menu and enable "Auto reload on JS change".

    Accessing logs #

    To view detailed logs on iOS, open your app in Xcode, then Build and Run your app on a device or the iPhone Simulator. The console should appear automatically after the app launches.

    Run adb logcat *:S ReactNative:V ReactNativeJS:V in a terminal to display the logs for an Android app running on a device or an 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.

    In Chrome, press Command⌘ + Option⌥ + I or select View → Developer → Developer Tools to toggle the developer tools console. Enable Pause On Caught Exceptions for a better debugging experience.

    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.

    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.

    FPS (Frames per Second) Monitor #

    You can enable a FPS graph overlay in the Developer Menu in order to help you debug performance problems.

    We are planning improvements to the React Native documentation. Your responses to this short survey will go a long way in helping us provide valuable content. Thank you!

    Take Survey
    © 2016 Facebook Inc.

    Debugging #

    Edit on GitHub

    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 the In-App Developer Menu #

    You can access the developer menu by shaking your device. 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 #

    Selecting Reload from the Developer Menu will reload the JavaScript that powers your application. You can also press Command⌘ + R in the iOS Simulator, or press R twice on Android emulators.

    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 in res/drawable folder on Android.
    • You have modified native code (Objective-C/Swift on iOS or Java/C++ on Android).

    Automatic reloading #

    You may enable Live Reload to automatically trigger a reload whenever your JavaScript code changes.

    Live Reload is available on iOS via the Developer Menu. On Android, select "Dev Settings" from the Developer Menu and enable "Auto reload on JS change".

    Accessing logs #

    To view detailed logs on iOS, open your app in Xcode, then Build and Run your app on a device or the iPhone Simulator. The console should appear automatically after the app launches.

    Run adb logcat *:S ReactNative:V ReactNativeJS:V in a terminal to display the logs for an Android app running on a device or an 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.

    In Chrome, press Command⌘ + Option⌥ + I or select View → Developer → Developer Tools to toggle the developer tools console. Enable Pause On Caught Exceptions for a better debugging experience.

    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.

    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.

    FPS (Frames per Second) Monitor #

    You can enable a FPS graph overlay in the Developer Menu in order to help you debug performance problems.

    We are planning improvements to the React Native documentation. Your responses to this short survey will go a long way in helping us provide valuable content. Thank you!

    Take Survey
    © 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 5abbb7ffb6e..59e0e5af6f0 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 5f46d10643e..5ec0e8469be 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 diff --git a/releases/next/docs/embedded-app-android.html b/releases/next/docs/embedded-app-android.html deleted file mode 100644 index f33b0e829c1..00000000000 --- a/releases/next/docs/embedded-app-android.html +++ /dev/null @@ -1,127 +0,0 @@ -Integrating with Existing Apps – React Native | A framework for building native apps using React

    Integrating with Existing Apps #

    Edit on GitHub

    Since React makes no assumptions about the rest of your technology stack, it's easily embeddable within an existing non-React Native app.

    Requirements #

    • an existing, gradle-based Android app
    • Node.js, see Getting Started for setup instructions

    Prepare your app #

    In your app's build.gradle file add the React Native dependency:

    compile "com.facebook.react:react-native:+" // From node_modules

    In your project's build.gradle file add an entry for the local React Native maven directory:

    allprojects { - repositories { - ... - maven { - // All of React Native (JS, Android binaries) is installed from npm - url "$rootDir/node_modules/react-native/android" - } - } - ... -}

    Next, make sure you have the Internet permission in your AndroidManifest.xml:

    <uses-permission android:name="android.permission.INTERNET" />

    This is only really used in dev mode when reloading JavaScript from the development server, so you can strip this in release builds if you need to.

    Add native code #

    You need to add some native code in order to start the React Native runtime and get it to render something. To do this, we're going to create an Activity that creates a ReactRootView, starts a React application inside it and sets it as the main content view.

    public class MyReactActivity extends Activity implements DefaultHardwareBackBtnHandler { - private ReactRootView mReactRootView; - private ReactInstanceManager mReactInstanceManager; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - mReactRootView = new ReactRootView(this); - mReactInstanceManager = ReactInstanceManager.builder() - .setApplication(getApplication()) - .setBundleAssetName("index.android.bundle") - .setJSMainModuleName("index.android") - .addPackage(new MainReactPackage()) - .setUseDeveloperSupport(BuildConfig.DEBUG) - .setInitialLifecycleState(LifecycleState.RESUMED) - .build(); - mReactRootView.startReactApplication(mReactInstanceManager, "MyAwesomeApp", null); - - setContentView(mReactRootView); - } - - @Override - public void invokeDefaultOnBackPressed() { - super.onBackPressed(); - } -}

    Next, we need to pass some activity lifecycle callbacks down to the ReactInstanceManager:

    @Override -protected void onPause() { - super.onPause(); - - if (mReactInstanceManager != null) { - mReactInstanceManager.onHostPause(); - } -} - -@Override -protected void onResume() { - super.onResume(); - - if (mReactInstanceManager != null) { - mReactInstanceManager.onHostResume(this, this); - } -} - -@Override -protected void onDestroy() { - super.onDestroy(); - - if (mReactInstanceManager != null) { - mReactInstanceManager.onHostDestroy(); - } -}

    We also need to pass back button events to React Native:

    @Override - public void onBackPressed() { - if (mReactInstanceManager != null) { - mReactInstanceManager.onBackPressed(); - } else { - super.onBackPressed(); - } -}

    This allows JavaScript to control what happens when the user presses the hardware back button (e.g. to implement navigation). When JavaScript doesn't handle a back press, your invokeDefaultOnBackPressed method will be called. By default this simply finishes your Activity. -Finally, we need to hook up the dev menu. By default, this is activated by (rage) shaking the device, but this is not very useful in emulators. So we make it show when you press the hardware menu button:

    @Override -public boolean onKeyUp(int keyCode, KeyEvent event) { - if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) { - mReactInstanceManager.showDevOptionsDialog(); - return true; - } - return super.onKeyUp(keyCode, event); -}

    That's it, your activity is ready to run some JavaScript code.

    Add JS to your app #

    In your app's root folder, run:

    $ npm init -$ npm install --save react-native -$ curl -o .flowconfig https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig

    This creates a node module for your app and adds the react-native npm dependency. Now open the newly created package.json file and add this under scripts:

    "start": "node node_modules/react-native/local-cli/cli.js start"

    Copy & paste the following code to index.android.js in your root folder — it's a barebones React Native app:

    'use strict'; - -import React from 'react'; -import { - AppRegistry, - StyleSheet, - Text, - View -} from 'react-native'; - -class MyAwesomeApp extends React.Component { - render() { - return ( - <View style={styles.container}> - <Text style={styles.hello}>Hello, World</Text> - </View> - ) - } -} -var styles = StyleSheet.create({ - container: { - flex: 1, - justifyContent: 'center', - }, - hello: { - fontSize: 20, - textAlign: 'center', - margin: 10, - }, -}); - -AppRegistry.registerComponent('MyAwesomeApp', () => MyAwesomeApp);

    Run your app #

    To run your app, you need to first start the development server. To do this, simply run the following command in your root folder:

    $ npm start

    Now build and run your Android app as normal (e.g. ./gradlew installDebug). Once you reach your React-powered activity inside the app, it should load the JavaScript code from the development server and display:

    Screenshot

    Sharing a ReactInstance across multiple Activities / Fragments in your app #

    You can have multiple Activities or Fragments that use the same ReactInstanceManager. You'll want to make your own "ReactFragment" or "ReactActivity" and have a singleton "holder" that holds a ReactInstanceManager. When you need the ReactInstanceManager / hook up the ReactInstanceManager to the lifecycle of those Activities or Fragments, use the one provided by the singleton.

    We are planning improvements to the React Native documentation. Your responses to this short survey will go a long way in helping us provide valuable content. Thank you!

    Take Survey
    © 2016 Facebook Inc.
    \ No newline at end of file diff --git a/releases/next/docs/embedded-app-ios.html b/releases/next/docs/embedded-app-ios.html deleted file mode 100644 index 365c06762e1..00000000000 --- a/releases/next/docs/embedded-app-ios.html +++ /dev/null @@ -1,104 +0,0 @@ -Integrating with Existing Apps – React Native | A framework for building native apps using React

    Integrating with Existing Apps #

    Edit on GitHub

    Since React makes no assumptions about the rest of your technology stack – it’s commonly noted as simply the V in MVC – it’s easily embeddable within an existing non-React Native app. In fact, it integrates with other best practice community tools like CocoaPods.

    Requirements #

    • CocoaPods – gem install cocoapods
    • Node.js
      • Install nvm with its setup instructions here. Then run nvm install node && nvm alias default node, which installs the latest version of Node.js and sets up your terminal so you can run it by typing node. With nvm you can install multiple versions of Node.js and easily switch between them.
    • Install the react-native package from npm by running the following command in the root directory of your project:
      • npm install react-native

    At this point you should have the React Native package installed under a directory named node_modules as a sibling to your .xcodeproj file.

    Install React Native Using CocoaPods #

    CocoaPods is a package management tool for iOS/Mac development. We need to use it to download React Native. If you haven't installed CocoaPods yet, check out this tutorial.

    When you are ready to work with CocoaPods, add the following lines to Podfile. If you don't have one, then create it under the root directory of your project.

    # Depending on how your project is organized, your node_modules directory may be -# somewhere else; tell CocoaPods where you've installed react-native from npm -pod 'React', :path => './node_modules/react-native', :subspecs => [ - 'Core', - 'RCTImage', - 'RCTNetwork', - 'RCTText', - 'RCTWebSocket', - # Add any other subspecs you want to use in your project -]

    Remember to install all subspecs you need. The <Text> element cannot be used without the RCTText subspec, for example.

    Then install your pods:

    $ pod install

    Create Your React Native App #

    There are two pieces you’ll need to set up:

    1. The root JavaScript file that will contain your actual React Native app and other components
    2. Wrapper Objective-C code that will load up your script and create a RCTRootView to display and manage your React Native components

    First, create a directory for your app’s React code and create a simple index.ios.js file:

    $ mkdir ReactComponent -$ touch ReactComponent/index.ios.js

    Copy & paste following starter code for index.ios.js – it’s a barebones React Native app:

    'use strict'; - -import React from 'react'; -import { - AppRegistry, - StyleSheet, - Text, - View -} from 'react-native'; - -var styles = StyleSheet.create({ - container: { - flex: 1, - backgroundColor: 'red' - } -}); - -class SimpleApp extends React.Component { - render() { - return ( - <View style={styles.container}> - <Text>This is a simple application.</Text> - </View> - ) - } -} - -AppRegistry.registerComponent('SimpleApp', () => SimpleApp);

    SimpleApp will be your module name, which will be used later on.

    Add Container View To Your App #

    You should now add a container view for the React Native component. It can be any UIView in your app.

    Container view example

    However, let's subclass UIView for the sake of clean code. Let's name it ReactView. Open up Yourproject.xcworkspace and create a new class ReactView (You can name it whatever you like :)).

    // ReactView.h - -#import <UIKit/UIKit.h> -@interface ReactView : UIView -@end

    In a view controller that wants to manage this view, go ahead and add an outlet and wire it up:

    // ViewController.m - -@interface ViewController () -@property (weak, nonatomic) IBOutlet ReactView *reactView; -@end

    NOTE For Swift apps there is no need for that.

    Here I disabled AutoLayout for simplicity. In real production world, you should turn on AutoLayout and setup constraints by yourself.

    Add RCTRootView To Container View #

    Ready for the most interesting part? Now we shall create the RCTRootView, where your React Native app lives.

    In ReactView.m, we need to first initiate RCTRootView with the URI of your index.ios.bundle. index.ios.bundle will be created by packager and served by React Native server, which will be discussed later on.

    NSURL *jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios"]; -// For production use, this `NSURL` could instead point to a pre-bundled file on disk: -// -// NSURL *jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"]; -// -// To generate that file, run the curl command and add the output to your main Xcode build target: -// -// curl http://localhost:8081/index.ios.bundle -o main.jsbundle -RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation - moduleName: @"SimpleApp" - initialProperties:nil - launchOptions:nil];

    Then add it as a subview of the ReactView.

    [self addSubview:rootView]; -rootView.frame = self.bounds;

    Swift apps #

    Add the following to ReactView.swift file:

    import UIKit -import React - -class ReactView: UIView { - - let rootView: RCTRootView = RCTRootView(bundleURL: NSURL(string: "http://localhost:8081/index.ios.bundle?platform=ios"), - moduleName: "SimpleApp", initialProperties: nil, launchOptions: nil) - - override func layoutSubviews() { - super.layoutSubviews() - - loadReact() - } - - func loadReact () { - addSubview(rootView) - rootView.frame = self.bounds - } -}

    And then make sure your view is added in a ViewContainer or story board file.

    Start Development Server #

    In root directory, we need to start React Native development server.

    (JS_DIR=`pwd`/ReactComponent; cd node_modules/react-native; npm run start -- --root $JS_DIR)

    This command will start up a React Native development server within our CocoaPods dependency to build our bundled script. The --root option indicates the root of your React Native apps – this will be our ReactComponent directory containing the single index.ios.js file. This running server will package up the index.ios.bundle file accessible via http://localhost:8081/index.ios.bundle.

    Update App Transport Security #

    On iOS 9 and above the app won't be a able to connect over http to localhost unless specifically told so. See this thread for alternatives and instructions: http://stackoverflow.com/questions/31254725/transport-security-has-blocked-a-cleartext-http.

    It is recommended that you add an App Transport Security exception for localhost in your app's Info.plist file:

    <key>NSAppTransportSecurity</key> -<dict> - <key>NSExceptionDomains</key> - <dict> - <key>localhost</key> - <dict> - <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key> - <true/> - </dict> - </dict> -</dict>

    If you don't do this, you will see the error - Could not connect to development server. when connecting to your server over http.

    Compile And Run #

    Now compile and run your app. You shall now see your React Native app running inside of the ReactView.

    Example

    Live reload and all of the debugging tools will work from the simulator. Just make sure that DEBUG=1 is set under Build Settings -> Preprocessor Macros. If you're using Cocoapods and a custom configuration (that is, not "Debug"), make sure you've specified it to be a debug configuration using the xcodeproj setting in your Podfile. Also make sure you've got a simple React component totally encapsulated behind an Objective-C UIView subclass.

    Conclusion #

    So under the hood, when RCTRootView is initialized, it will try to download, parse and run the bundle file from React Native development server. This means all you need to do is to implement your own container view or view controller for the RCTRootView – the RCTRootView ingests your bundled JS and renders your React components. Bravo!

    You can checkout full source code of a sample application here.

    We are planning improvements to the React Native documentation. Your responses to this short survey will go a long way in helping us provide valuable content. Thank you!

    Take Survey
    © 2016 Facebook Inc.
    \ No newline at end of file diff --git a/releases/next/docs/flexbox.html b/releases/next/docs/flexbox.html index 39ab86fb1e8..c7ab56c8043 100644 --- a/releases/next/docs/flexbox.html +++ b/releases/next/docs/flexbox.html @@ -1,4 +1,4 @@ -Flexbox – React Native | A framework for building native apps using React

    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.

    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.

    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 diff --git a/releases/next/docs/gesture-responder-system.html b/releases/next/docs/gesture-responder-system.html index 2186e2c76bf..17d2eac07cf 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.

    We are planning improvements to the React Native documentation. Your responses to this short survey will go a long way in helping us provide valuable content. Thank you!

    Take Survey
    © 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.

    We are planning improvements to the React Native documentation. Your responses to this short survey will go a long way in helping us provide valuable content. Thank you!

    Take Survey
    © 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
    +Platform: +Objective-C +Swift +Android +
    + +
    + +

    This section will be updated shortly showing an integration into a more real world application such as the 2048 app that was used for Objective-C and Swift.

    + +

    Key Concepts #

    React Native is great when you are starting a new mobile app from scratch. However, it also works well for adding a single view or user flow to existing native applications. With a few steps, you can add new React Native based features, screens, views, etc.

    + +

    The keys to integrating React Native components into your iOS application are to:

    1. Understand what React Native components you want to integrate.
    2. Create a Podfile with subspecs for all the React Native components you will need for your integration.
    3. Create your actual React Native components in JavaScript.
    4. Add a new event handler that creates a RCTRootView that points to your React Native component and its AppRegistry name that you defined in index.ios.js.
    5. Start the React Native server and run your native application.
    6. Optionally add more React Native components.
    7. Debug.
    8. Prepare for deployment (e.g., via the react-native-xcode.sh script).
    9. Deploy and Profit!
    + +

    The keys to integrating React Native components into your iOS application are to:

    1. Understand what React Native components you want to integrate.
    2. Install react-native in your Android application root directory to create node_modules/ directory.
    3. Create your actual React Native components in JavaScript.
    4. Add com.facebook.react:react-native:+ and a maven pointing to the react-native binaries in node_nodules/ to your build.gradle file.
    5. Create a custom React Native specific Activity that creates a ReactRootView.
    6. Start the React Native server and run your native application.
    7. Optionally add more React Native components.
    8. Debug.
    9. Prepare for deployment.
    10. Deploy and Profit!
    + +

    Prerequisites #

    + +

    The Android Getting Started guide will install the appropriate prerequisites (e.g., npm) for React Native on the Android target platform and your chosen development environment.

    + +

    General #

    First, follow the Getting Started guide for your development environment and the iOS target platform to install the prerequisites for React Native.

    CocoaPods #

    CocoaPods is a package management tool for iOS and Mac development. We use it to add the actual React Native framework code locally into your current project.

    $ sudo gem install cocoapods

    It is technically possible not to use CocoaPods, but this requires manual library and linker additions that overly complicates this process.

    Our Sample App #

    + +

    Assume the app for integration is a 2048 game. Here is what the main menu of the native application looks like without React Native.

    + +

    Assume the app for integration is a 2048 game. Here is what the main menu of the native application looks like without React Native.

    + +

    Before RN Integration

    Package Dependencies #

    React Native integration requires both the React and React Native node modules. The React Native Framework will provide the code to allow your application integration to happen.

    package.json #

    We will add the package dependencies to a package.json file. Create this file in the root of your project if it does not exist.

    Normally with React Native projects, you will put files like package.json, index.ios.js, etc. in the root directory of your project and then have your iOS specific native code in a subdirectory like ios/ where your Xcode project is located (e.g., .xcodeproj).

    Below is an example of what your package.json file should minimally contain.

    Version numbers will vary according to your needs. Normally the latest versions for both React and React Native will be sufficient.

    + +
    { + "name": "NumberTileGame", + "version": "0.0.1", + "private": true, + "scripts": { + "start": "node node_modules/react-native/local-cli/cli.js start" + }, + "dependencies": { + "react": "15.0.2", + "react-native": "0.26.1" + } +}
    + +
    { + "name": "swift-2048", + "version": "0.0.1", + "private": true, + "scripts": { + "start": "node node_modules/react-native/local-cli/cli.js start" + }, + "dependencies": { + "react": "15.0.2", + "react-native": "0.26.1" + } +}
    + +

    Packages Installation #

    Install the React and React Native modules via the Node package manager. The Node modules will be installed into a node_modules/ directory in the root of your project.

    # From the directory containing package.json project, install the modules +# The modules will be installed in node_modules/ +$ npm install

    React Native Framework #

    The React Native Framework was installed as Node module in your project above. We will now install a CocoaPods Podfile with the components you want to use from the framework itself.

    Subspecs #

    Before you integrate React Native into your application, you will want to decide what parts of the React Native Framework you would like to integrate. That is where subspecs come in. When you create your Podfile, you are going to specify React Native library dependencies that you will want installed so that your application can use those libraries. Each library will become a subspec in the Podfile.

    The list of supported subspecs are in node_modules/react-native/React.podspec. They are generally named by functionality. For example, you will generally always want the Core subspec. That will get you the AppRegistry, StyleSheet, View and other core React Native libraries. If you want to add the React Native Text library (e.g., for <Text> elements), then you will need the RCTText subspec. If you want the Image library (e.g., for <Image> elements), then you will need the RCTImage subspec.

    Podfile #

    After you have used Node to install the React and React Native frameworks into the node_modules directory, and you have decided on what React Native elements you want to integrate, you are ready to create your Podfile so you can install those components for use in your application.

    The easiest way to create a Podfile is by using the CocoaPods init command in the native iOS code directory of your project:

    ## In the directory where your native iOS code is located (e.g., where your `.xcodeproj` file is located) +$ pod init

    The Podfile will be created and saved in the iOS directory (e.g., ios/) of your current project and will contain a boilerplate setup that you will tweak for your integration purposes. In the end, Podfile should look something similar to this:

    + +
    # The target name is most likely the name of your project. +target 'NumberTileGame' do + + # Your 'node_modules' directory is probably in the root of your project, + # but if not, adjust the `:path` accordingly + pod 'React', :path => '../node_modules/react-native', :subspecs => [ + 'Core', + 'RCTText', + 'RCTWebSocket', # needed for debugging + # Add any other subspecs you want to use in your project + ] + +end
    + +
    source 'https://github.com/CocoaPods/Specs.git' + +# Required for Swift apps +platform :ios, '8.0' +use_frameworks! + +# The target name is most likely the name of your project. +target 'swift-2048' do + + # Your 'node_modules' directory is probably in the root of your project, + # but if not, adjust the `:path` accordingly + pod 'React', :path => '../node_modules/react-native', :subspecs => [ + 'Core', + 'RCTText', + 'RCTWebSocket', # needed for debugging + # Add any other subspecs you want to use in your project + ] + +end
    + +

    Pod Installation #

    After you have created your Podfile, you are ready to install the React Native pod.

    $ pod install

    Your should see output such as:

    Analyzing dependencies +Fetching podspec for `React` from `../node_modules/react-native` +Downloading dependencies +Installing React (0.26.0) +Generating Pods project +Integrating client project +Sending stats +Pod installation complete! There are 3 dependencies from the Podfile and 1 total pod installed.
    + +

    If you get a warning such as "The swift-2048 [Debug] target overrides the FRAMEWORK_SEARCH_PATHS build setting defined in Pods/Target Support Files/Pods-swift-2048/Pods-swift-2048.debug.xcconfig. This can lead to problems with the CocoaPods installation", then make sure the Framework Search Paths in Build Settings for both Debug and Release only contain $(inherited).

    + +

    Code Integration #

    Now that we have a package foundation, we will actually modify the native application to integrate React Native into the application. For our 2048 app, we will add a "High Score" screen in React Native.

    The React Native component #

    The first bit of code we will write is the actual React Native code for the new "High Score" screen that will be integrated into our application.

    Create a index.ios.js file #

    First, create an empty index.ios.js file. For ease, I am doing this in the root of the project.

    index.ios.js is the starting point for React Native applications on iOS. And it is always required. It can be a small file that requires other file that are part of your React Native component or application, or it can contain all the code that is needed for it. In our case, we will just put everything in index.ios.js

    # In root of your project +$ touch index.ios.js

    Add Your React Native Code #

    In your index.ios.js, create your component. In our sample here, we will add simple <Text> component within a styled <View>

    'use strict'; + +import React from 'react'; +import { + AppRegistry, + StyleSheet, + Text, + View +} from 'react-native'; + +class RNHighScores extends React.Component { + render() { + var contents = this.props["scores"].map( + score => <Text key={score.name}>{score.name}:{score.value}{"\n"}</Text> + ); + return ( + <View style={styles.container}> + <Text style={styles.highScoresTitle}> + 2048 High Scores! + </Text> + <Text style={styles.scores}> + {contents} + </Text> + </View> + ); + } +} + +const styles = StyleSheet.create({ + container: { + flex: 1, + justifyContent: 'center', + alignItems: 'center', + backgroundColor: '#FFFFFF', + }, + highScoresTitle: { + fontSize: 20, + textAlign: 'center', + margin: 10, + }, + scores: { + textAlign: 'center', + color: '#333333', + marginBottom: 5, + }, +}); + +// Module name +AppRegistry.registerComponent('RNHighScores', () => RNHighScores);

    RNHighScores is the name of your module that will be used when you add a view to React Native from within your iOS application.

    The Magic: RCTRootView #

    Now that your React Native component is created via index.ios.js, you need to add that component to a new or existing ViewController. The easiest path is to take is to optionally create an event path to your component and then add that component to an existing ViewController.

    We will tie our React Native component with a new native view in the ViewController that will actually host it called RCTRootView .

    Create an Event Path #

    You can add a new link on the main game menu to go to the "High Score" React Native page.

    Event Path

    Event Handler #

    We will now add an event handler from the menu link. A method will be added to the main ViewController of your application. This is where RCTRootView comes into play.

    When you build a React Native application, you use the React Native packager to create an index.ios.bundle that will be served by the React Native server. Inside index.ios.bundle will be our RNHighScore module. So, we need to point our RCTRootView to the location of the index.ios.bundle resource (via NSURL) and tie it to the module.

    We will, for debugging purposes, log that the event handler was invoked. Then, we will create a string with the location of our React Native code that exists inside the index.ios.bundle. Finally, we will create the main RCTRootView. Notice how we provide RNHighScores as the moduleName that we created above when writing the code for our React Native component.

    + +

    First import the RCTRootView library.

    #import "RCTRootView.h"

    The initialProperties are here for illustration purposes so we have some data for our high score screen. In our React Native component, we will use this.props to get access to that data.

    - (IBAction)highScoreButtonPressed:(id)sender { + NSLog(@"High Score Button Pressed"); + NSURL *jsCodeLocation = [NSURL + URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios"]; + RCTRootView *rootView = + [[RCTRootView alloc] initWithBundleURL : jsCodeLocation + moduleName : @"RNHighScores" + initialProperties : + @{ + @"scores" : @[ + @{ + @"name" : @"Alex", + @"value": @"42" + }, + @{ + @"name" : @"Joel", + @"value": @"10" + } + ] + } + launchOptions : nil]; + UIViewController *vc = [[UIViewController alloc] init]; + vc.view = rootView; + [self presentViewController:vc animated:YES completion:nil]; +}

    Note that RCTRootView initWithURL starts up a new JSC VM. To save resources and simplify the communication between RN views in different parts of your native app, you can have multiple views powered by React Native that are associated with a single JS runtime. To do that, instead of using [RCTRootView alloc] initWithURL, use RCTBridge initWithBundleURL to create a bridge and then use RCTRootView initWithBridge.

    + +

    First import the React library.

    import React

    The initialProperties are here for illustration purposes so we have some data for our high score screen. In our React Native component, we will use this.props to get access to that data.

    @IBAction func highScoreButtonTapped(sender : UIButton) { + NSLog("Hello") + let jsCodeLocation = NSURL(string: "http://localhost:8081/index.ios.bundle?platform=ios") + let mockData:NSDictionary = ["scores": + [ + ["name":"Alex", "value":"42"], + ["name":"Joel", "value":"10"] + ] + ] + + let rootView = RCTRootView( + bundleURL: jsCodeLocation, + moduleName: "RNHighScores", + initialProperties: mockData as [NSObject : AnyObject], + launchOptions: nil + ) + let vc = UIViewController() + vc.view = rootView + self.presentViewController(vc, animated: true, completion: nil) +}

    Note that RCTRootView bundleURL starts up a new JSC VM. To save resources and simplify the communication between RN views in different parts of your native app, you can have multiple views powered by React Native that are associated with a single JS runtime. To do that, instead of using RCTRootView bundleURL, use RCTBridge initWithBundleURL to create a bridge and then use RCTRootView initWithBridge.

    + +

    When moving your app to production, the NSURL can point to a pre-bundled file on disk via something like [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];. You can use the react-native-xcode.sh script in node_modules/react-native/packager/ to generate that pre-bundled file.

    + +

    When moving your app to production, the NSURL can point to a pre-bundled file on disk via something like let mainBundle = NSBundle(URLForResource: "main" withExtension:"jsbundle"). You can use the react-native-xcode.sh script in node_modules/react-native/packager/ to generate that pre-bundled file.

    + +

    Wire Up #

    Wire up the new link in the main menu to the newly added event handler method.

    Event Path

    One of the easier ways to do this is to open the view in the storyboard and right click on the new link. Select something such as the Touch Up Inside event, drag that to the storyboard and then select the created method from the list provided.

    Test Your Integration #

    You have now done all the basic steps to integrate React Native with your current application. Now we will start the React Native packager to build the index.ios.bundle packager and the server running on localhost to serve it.

    App Transport Security #

    Apple has blocked implicit cleartext HTTP resource loading. So we need to add the following our project's Info.plist (or equivalent) file.

    <key>NSAppTransportSecurity</key> +<dict> + <key>NSExceptionDomains</key> + <dict> + <key>localhost</key> + <dict> + <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key> + <true/> + </dict> + </dict> +</dict>

    Run the Packager #

    # From the root of your project, where the `node_modules` directory is located. +$ npm start

    Run the App #

    If you are using Xcode or your favorite editor, build and run your native iOS application as normal. Alternatively, you can run the app from the command line using:

    # From the root of your project +$ react-native run-ios

    In our sample application, you should see the link to the "High Scores" and then when you click on that you will see the rendering of your React Native component.

    Here is the native application home screen:

    Home Screen

    Here is the React Native high score screen:

    High Scores

    If you are getting module resolution issues when running your application please see this GitHub issue for information and possible resolution. This comment seemed to be the latest possible resolution.

    See the Code #

    + +

    You can examine the code that added the React Native screen on GitHub.

    + +

    You can examine the code that added the React Native screen on GitHub.

    + +

    Add JS to your app #

    In your app's root folder, run:

    $ npm init +$ npm install --save react-native +$ curl -o .flowconfig https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig

    This creates a node module for your app and adds the react-native npm dependency. Now open the newly created package.json file and add this under scripts:

    "start": "node node_modules/react-native/local-cli/cli.js start"

    Copy & paste the following code to index.android.js in your root folder — it's a barebones React Native app:

    'use strict'; + +import React from 'react'; +import { + AppRegistry, + StyleSheet, + Text, + View +} from 'react-native'; + +class HelloWorld extends React.Component { + render() { + return ( + <View style={styles.container}> + <Text style={styles.hello}>Hello, World</Text> + </View> + ) + } +} +var styles = StyleSheet.create({ + container: { + flex: 1, + justifyContent: 'center', + }, + hello: { + fontSize: 20, + textAlign: 'center', + margin: 10, + }, +}); + +AppRegistry.registerComponent('HelloWorld', () => HelloWorld);

    Prepare your current app #

    In your app's build.gradle file add the React Native dependency:

    compile "com.facebook.react:react-native:+" // From node_modules

    In your project's build.gradle file add an entry for the local React Native maven directory:

    allprojects { + repositories { + ... + maven { + // All of React Native (JS, Android binaries) is installed from npm + url "$rootDir/node_modules/react-native/android" + } + } + ... +}

    Next, make sure you have the Internet permission in your AndroidManifest.xml:

    <uses-permission android:name="android.permission.INTERNET" />

    This is only really used in dev mode when reloading JavaScript from the development server, so you can strip this in release builds if you need to.

    Add native code #

    You need to add some native code in order to start the React Native runtime and get it to render something. To do this, we're going to create an Activity that creates a ReactRootView, starts a React application inside it and sets it as the main content view.

    public class MyReactActivity extends Activity implements DefaultHardwareBackBtnHandler { + private ReactRootView mReactRootView; + private ReactInstanceManager mReactInstanceManager; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + mReactRootView = new ReactRootView(this); + mReactInstanceManager = ReactInstanceManager.builder() + .setApplication(getApplication()) + .setBundleAssetName("index.android.bundle") + .setJSMainModuleName("index.android") + .addPackage(new MainReactPackage()) + .setUseDeveloperSupport(BuildConfig.DEBUG) + .setInitialLifecycleState(LifecycleState.RESUMED) + .build(); + mReactRootView.startReactApplication(mReactInstanceManager, "HelloWorld", null); + + setContentView(mReactRootView); + } + + @Override + public void invokeDefaultOnBackPressed() { + super.onBackPressed(); + } +}

    A ReactInstanceManager can be shared amongst multiple activities and/or fragments. You will want to make your own ReactFragment or ReactActivity and have a singleton holder that holds a ReactInstanceManager. When you need the ReactInstanceManager (e.g., to hook up the ReactInstanceManager to the lifecycle of those Activities or Fragments) use the one provided by the singleton.

    Next, we need to pass some activity lifecycle callbacks down to the ReactInstanceManager:

    @Override +protected void onPause() { + super.onPause(); + + if (mReactInstanceManager != null) { + mReactInstanceManager.onHostPause(); + } +} + +@Override +protected void onResume() { + super.onResume(); + + if (mReactInstanceManager != null) { + mReactInstanceManager.onHostResume(this, this); + } +} + +@Override +protected void onDestroy() { + super.onDestroy(); + + if (mReactInstanceManager != null) { + mReactInstanceManager.onHostDestroy(); + } +}

    We also need to pass back button events to React Native:

    @Override + public void onBackPressed() { + if (mReactInstanceManager != null) { + mReactInstanceManager.onBackPressed(); + } else { + super.onBackPressed(); + } +}

    This allows JavaScript to control what happens when the user presses the hardware back button (e.g. to implement navigation). When JavaScript doesn't handle a back press, your invokeDefaultOnBackPressed method will be called. By default this simply finishes your Activity.

    Finally, we need to hook up the dev menu. By default, this is activated by (rage) shaking the device, but this is not very useful in emulators. So we make it show when you press the hardware menu button:

    @Override +public boolean onKeyUp(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) { + mReactInstanceManager.showDevOptionsDialog(); + return true; + } + return super.onKeyUp(keyCode, event); +}

    That's it, your activity is ready to run some JavaScript code.

    Run your app #

    To run your app, you need to first start the development server. To do this, simply run the following command in your root folder:

    $ npm start

    Now build and run your Android app as normal (e.g. ./gradlew installDebug). Once you reach your React-powered activity inside the app, it should load the JavaScript code from the development server and display:

    Screenshot

    +

    We are planning improvements to the React Native documentation. Your responses to this short survey will go a long way in helping us provide valuable content. Thank you!

    Take Survey
    © 2016 Facebook Inc.
    \ No newline at end of file diff --git a/releases/next/docs/upgrading.html b/releases/next/docs/upgrading.html index dbedfd267bb..2b511cf3d2f 100644 --- a/releases/next/docs/upgrading.html +++ b/releases/next/docs/upgrading.html @@ -1,4 +1,4 @@ -Upgrading – React Native | A framework for building native apps using React

    Upgrading #

    Edit on GitHub

    Upgrading to new versions of React Native will give you access to more APIs, views, developer tools +Upgrading – React Native | A framework for building native apps using React

    Upgrading #

    Edit on GitHub

    Upgrading to new versions of React Native will give you access to more APIs, views, developer tools and other goodies. Because React Native projects are essentially made up of an Android project, an iOS project and a JavaScript project, all combined under an npm package, upgrading can be rather tricky. But we try to make it easy for you. Here's what you need to do to upgrade from an older diff --git a/releases/next/docs/vibration.html b/releases/next/docs/vibration.html index e92e634369a..7601242b79e 100644 --- a/releases/next/docs/vibration.html +++ b/releases/next/docs/vibration.html @@ -1,4 +1,4 @@ -Vibration – React Native | A framework for building native apps using React

    Vibration #

    Edit on GitHub

    The Vibration API is exposed at Vibration.vibrate(). +Vibration – React Native | A framework for building native apps using React

    Vibration #

    Edit on GitHub

    The Vibration API is exposed at Vibration.vibrate(). The vibration is asynchronous so this method will return immediately.

    There will be no effect on devices that do not support Vibration, eg. the simulator.

    Note for android add <uses-permission android:name="android.permission.VIBRATE"/> to AndroidManifest.xml

    Vibration patterns are currently unsupported.

    Methods #

    static vibrate(pattern, repeat) #

    static cancel() #

    Stop vibration

    @platform android

    Examples #

    Edit on GitHub
    'use strict'; diff --git a/releases/next/docs/vibrationios.html b/releases/next/docs/vibrationios.html index bed86445de1..0b2a5eeb1b8 100644 --- a/releases/next/docs/vibrationios.html +++ b/releases/next/docs/vibrationios.html @@ -1,4 +1,4 @@ -VibrationIOS – React Native | A framework for building native apps using React

    VibrationIOS #

    Edit on GitHub

    NOTE: VibrationIOS is being deprecated. Use Vibration instead.

    The Vibration API is exposed at VibrationIOS.vibrate(). On iOS, calling this +VibrationIOS – React Native | A framework for building native apps using React

    VibrationIOS #

    Edit on GitHub

    NOTE: VibrationIOS is being deprecated. Use Vibration instead.

    The Vibration API is exposed at VibrationIOS.vibrate(). On iOS, calling this function will trigger a one second vibration. The vibration is asynchronous so this method will return immediately.

    There will be no effect on devices that do not support Vibration, eg. the iOS simulator.

    Vibration patterns are currently unsupported.

    Methods #

    static vibrate() #

    @deprecated

    Examples #

    Edit on GitHub
    'use strict'; diff --git a/releases/next/docs/videos.html b/releases/next/docs/videos.html index 9d9c702dce6..dcfda785867 100644 --- a/releases/next/docs/videos.html +++ b/releases/next/docs/videos.html @@ -1,4 +1,4 @@ -Videos – React Native | A framework for building native apps using React

    Videos #

    Edit on GitHub

    React.js Conf 2016 #

    +Videos – React Native | A framework for building native apps using React

    Videos #

    Edit on GitHub

    React.js Conf 2016 #

    diff --git a/releases/next/docs/view.html b/releases/next/docs/view.html index de615c59a1e..619d5e80a1e 100644 --- a/releases/next/docs/view.html +++ b/releases/next/docs/view.html @@ -1,4 +1,4 @@ -View – React Native | A framework for building native apps using React

    View #

    Edit on GitHub

    The most fundamental component for building UI, View is a +View – React Native | A framework for building native apps using React

    View #

    Edit on GitHub

    The most fundamental component for building UI, View is a container that supports layout with flexbox, style, some touch handling, and accessibility controls, and is designed to be nested inside other views and to have 0 to many children of any type. View maps directly to the native diff --git a/releases/next/docs/viewpagerandroid.html b/releases/next/docs/viewpagerandroid.html index 80b5e7b4025..319566862d9 100644 --- a/releases/next/docs/viewpagerandroid.html +++ b/releases/next/docs/viewpagerandroid.html @@ -1,4 +1,4 @@ -ViewPagerAndroid – React Native | A framework for building native apps using React

    ViewPagerAndroid #

    Edit on GitHub

    Container that allows to flip left and right between child views. Each +ViewPagerAndroid – React Native | A framework for building native apps using React

    ViewPagerAndroid #

    Edit on GitHub

    Container that allows to flip left and right between child views. Each child view of the ViewPagerAndroid will be treated as a separate page and will be stretched to fill the ViewPagerAndroid.

    It is important all children are <View>s and not composite components. You can set style properties like padding or backgroundColor for each diff --git a/releases/next/docs/webview.html b/releases/next/docs/webview.html index 1da07817f64..941a61a6f67 100644 --- a/releases/next/docs/webview.html +++ b/releases/next/docs/webview.html @@ -1,4 +1,4 @@ -WebView – React Native | A framework for building native apps using React

    WebView #

    Edit on GitHub

    Renders a native WebView.

    Props #

    automaticallyAdjustContentInsets bool #

    contentInset {top: number, left: number, bottom: number, right: number} #

    html string #

    Deprecated

    Use the source prop instead.

    injectedJavaScript string #

    Sets the JS to be injected when the webpage loads.

    mediaPlaybackRequiresUserAction bool #

    Determines whether HTML5 audio & videos require the user to tap before they can +WebView – React Native | A framework for building native apps using React

    WebView #

    Edit on GitHub

    Renders a native WebView.

    Props #

    automaticallyAdjustContentInsets bool #

    contentInset {top: number, left: number, bottom: number, right: number} #

    html string #

    Deprecated

    Use the source prop instead.

    injectedJavaScript string #

    Sets the JS to be injected when the webpage loads.

    mediaPlaybackRequiresUserAction bool #

    Determines whether HTML5 audio & videos require the user to tap before they can start playing. The default value is false.

    onError function #

    Invoked when load fails

    onLoad function #

    Invoked when load finish

    onLoadEnd function #

    Invoked when load either succeeds or fails

    onLoadStart function #

    Invoked on load start

    onNavigationStateChange function #

    renderError function #

    Function that returns a view to show if there's an error.

    renderLoading function #

    Function that returns a loading indicator.

    scalesPageToFit bool #

    Sets whether the webpage scales to fit the view and the user can change the scale.

    source {uri: string, method: string, headers: object, body: string}, {html: string, baseUrl: string}, number #

    Loads static html or a uri (with optional headers) in the WebView.

    startInLoadingState bool #

    url string #

    Deprecated

    Use the source prop instead.

    androiddomStorageEnabled bool #

    Used on Android only, controls whether DOM Storage is enabled or not

    androidjavaScriptEnabled bool #

    Used on Android only, JS is enabled by default for WebView on iOS

    iosallowsInlineMediaPlayback bool #

    Determines whether HTML5 videos play inline or use the native full-screen controller. default value false diff --git a/releases/next/img/react-native-add-react-native-integration-example-high-scores.png b/releases/next/img/react-native-add-react-native-integration-example-high-scores.png new file mode 100644 index 00000000000..6d07707ba86 Binary files /dev/null and b/releases/next/img/react-native-add-react-native-integration-example-high-scores.png differ diff --git a/releases/next/img/react-native-add-react-native-integration-example-home-screen.png b/releases/next/img/react-native-add-react-native-integration-example-home-screen.png new file mode 100644 index 00000000000..2b1b8b28735 Binary files /dev/null and b/releases/next/img/react-native-add-react-native-integration-example-home-screen.png differ diff --git a/releases/next/img/react-native-add-react-native-integration-link.png b/releases/next/img/react-native-add-react-native-integration-link.png new file mode 100644 index 00000000000..3d89eaf020a Binary files /dev/null and b/releases/next/img/react-native-add-react-native-integration-link.png differ diff --git a/releases/next/img/react-native-add-react-native-integration-wire-up.png b/releases/next/img/react-native-add-react-native-integration-wire-up.png new file mode 100644 index 00000000000..43d2add57ba Binary files /dev/null and b/releases/next/img/react-native-add-react-native-integration-wire-up.png differ diff --git a/releases/next/img/react-native-existing-app-integration-ios-before.png b/releases/next/img/react-native-existing-app-integration-ios-before.png new file mode 100644 index 00000000000..445dd790444 Binary files /dev/null and b/releases/next/img/react-native-existing-app-integration-ios-before.png differ