From 4e368f7421676e3070c4bd2e3ebc00ab05a7aa06 Mon Sep 17 00:00:00 2001 From: Website Deployment Script Date: Tue, 1 Mar 2016 15:43:07 +0000 Subject: [PATCH] Updated docs for 0.21 --- docs/accessibility.html | 14 +-- docs/actionsheetios.html | 4 +- docs/activityindicatorios.html | 4 +- docs/alert.html | 10 +- docs/alertios.html | 10 +- docs/android-building-from-source.html | 12 +-- docs/android-setup.html | 6 +- docs/android-ui-performance.html | 2 +- docs/animated.html | 46 ++++----- docs/animations.html | 39 ++++---- docs/appregistry.html | 4 +- docs/appstate.html | 12 +-- docs/appstateios.html | 14 +-- docs/asyncstorage.html | 20 ++-- docs/backandroid.html | 4 +- docs/cameraroll.html | 8 +- docs/colors.html | 2 +- docs/communication-ios.html | 15 ++- docs/datepickerandroid.html | 133 +++++++++++++++++++++++++ docs/datepickerios.html | 10 +- docs/debugging.html | 2 +- docs/dimensions.html | 4 +- docs/direct-manipulation.html | 16 +-- docs/drawerlayoutandroid.html | 10 +- docs/embedded-app-android.html | 11 +- docs/embedded-app-ios.html | 17 ++-- docs/flexbox.html | 2 +- docs/geolocation.html | 14 +-- docs/gesture-responder-system.html | 2 +- docs/getting-started-on-linux.html | 35 +++++++ docs/getting-started.html | 3 +- docs/image.html | 22 ++-- docs/images.html | 10 +- docs/intentandroid.html | 14 +-- docs/interactionmanager.html | 6 +- docs/javascript-environment.html | 2 +- docs/known-issues.html | 8 +- docs/layoutanimation.html | 6 +- docs/linking-libraries-ios.html | 12 +-- docs/linking.html | 26 ++--- docs/linkingios.html | 14 +-- docs/linux-windows-support.html | 4 +- docs/listview.html | 32 +++--- docs/mapview.html | 28 +++--- docs/modal.html | 6 +- docs/native-components-android.html | 16 +-- docs/native-components-ios.html | 18 ++-- docs/native-modules-android.html | 24 ++--- docs/native-modules-ios.html | 28 +++--- docs/nativemethodsmixin.html | 12 +-- docs/navigator-comparison.html | 4 +- docs/navigator.html | 20 ++-- docs/navigatorios.html | 14 +-- docs/netinfo.html | 12 +-- docs/network.html | 34 ++++--- docs/panresponder.html | 12 +-- docs/performance.html | 38 +++---- docs/picker.html | 8 +- docs/pickerios.html | 4 +- docs/pixelratio.html | 8 +- docs/platform-specific-code.html | 12 +-- docs/progressbarandroid.html | 8 +- docs/progressviewios.html | 4 +- docs/pulltorefreshviewandroid.html | 6 +- docs/pushnotificationios.html | 27 +++-- docs/refreshcontrol.html | 6 +- docs/running-on-device-android.html | 4 +- docs/running-on-device-ios.html | 2 +- docs/scrollview.html | 68 ++++++------- docs/segmentedcontrolios.html | 12 +-- docs/shadowproptypesios.html | 12 +++ docs/signed-apk-android.html | 10 +- docs/sliderios.html | 24 ++--- docs/statusbar.html | 12 +-- docs/statusbarios.html | 4 +- docs/style.html | 10 +- docs/stylesheet.html | 6 +- docs/switch.html | 8 +- docs/tabbarios-item.html | 12 +-- docs/tabbarios.html | 4 +- docs/testing.html | 4 +- docs/text.html | 16 +-- docs/textinput.html | 32 +++--- docs/timepickerandroid.html | 128 ++++++++++++++++++++++++ docs/timers.html | 6 +- docs/toastandroid.html | 6 +- docs/toolbarandroid.html | 16 +-- docs/touchablehighlight.html | 8 +- docs/touchablenativefeedback.html | 6 +- docs/touchableopacity.html | 6 +- docs/touchablewithoutfeedback.html | 8 +- docs/transforms.html | 2 +- docs/troubleshooting.html | 12 +-- docs/tutorial.html | 14 +-- docs/upgrading.html | 6 +- docs/vibrationios.html | 6 +- docs/videos.html | 8 +- docs/view.html | 42 ++++---- docs/viewpagerandroid.html | 16 +-- docs/webview.html | 10 +- index.html | 4 +- showcase.html | 2 +- support.html | 2 +- versions.html | 2 +- 104 files changed, 932 insertions(+), 608 deletions(-) create mode 100644 docs/datepickerandroid.html create mode 100644 docs/getting-started-on-linux.html create mode 100644 docs/shadowproptypesios.html create mode 100644 docs/timepickerandroid.html diff --git a/docs/accessibility.html b/docs/accessibility.html index 888ad72b03c..57836b28e4d 100644 --- a/docs/accessibility.html +++ b/docs/accessibility.html @@ -1,23 +1,23 @@ -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}> +</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}> <View style={styles.button}> <Text style={styles.buttonText}>Press me!</Text> </View> -</TouchableOpacity>

In the above example, the accessibilityLabel on the TouchableOpacity element would default to "Press me!". The label is constructed by concatenating all Text node children separated by spaces.

accessibilityTraits (iOS) #

Accessibility traits tell a person using VoiceOver what kind of element they have selected. Is this element a label? A button? A header? These questions are answered by accessibilityTraits.

To use, set the accessibilityTraits property to one of (or an array of) accessibility trait strings:

  • none Used when the element has no traits.
  • button Used when the element should be treated as a button.
  • link Used when the element should be treated as a link.
  • header Used when an element acts as a header for a content section (e.g. the title of a navigation bar).
  • search Used when the text field element should also be treated as a search field.
  • image Used when the element should be treated as an image. Can be combined with button or link, for example.
  • selected Used when the element is selected. For example, a selected row in a table or a selected button within a segmented control.
  • plays Used when the element plays its own sound when activated.
  • key Used when the element acts as a keyboard key.
  • text Used when the element should be treated as static text that cannot change.
  • summary Used when an element can be used to provide a quick summary of current conditions in the app when the app first launches. For example, when Weather first launches, the element with today's weather conditions is marked with this trait.
  • disabled Used when the control is not enabled and does not respond to user input.
  • frequentUpdates Used when the element frequently updates its label or value, but too often to send notifications. Allows an accessibility client to poll for changes. A stopwatch would be an example.
  • startsMedia Used when activating an element starts a media session (e.g. playing a movie, recording audio) that should not be interrupted by output from an assistive technology, like VoiceOver.
  • adjustable Used when an element can be "adjusted" (e.g. a slider).
  • allowsDirectInteraction Used when an element allows direct touch interaction for VoiceOver users (for example, a view representing a piano keyboard).
  • pageTurn Informs VoiceOver that it should scroll to the next page when it finishes reading the contents of the element.

onAccessibilityTap (iOS) #

Use this property to assign a custom function to be called when someone activates an accessible element by double tapping on it while it's selected.

onMagicTap (iOS) #

Assign this property to a custom function which will be called when someone performs the "magic tap" gesture, which is a double-tap with two fingers. A magic tap function should perform the most relevant action a user could take on a component. In the Phone app on iPhone, a magic tap answers a phone call, or ends the current one. If the selected element does not have an onMagicTap function, the system will traverse up the view hierarchy until it finds a view that does.

accessibilityComponentType (Android) #

In some cases, we also want to alert the end user of the type of selected component (i.e., that it is a “button”). If we were using native buttons, this would work automatically. Since we are using javascript, we need to provide a bit more context for TalkBack. To do so, you must specify the ‘accessibilityComponentType’ property for any UI component. For instances, we support ‘button’, ‘radiobutton_checked’ and ‘radiobutton_unchecked’ and so on.

<TouchableWithoutFeedback accessibilityComponentType=”button” +</TouchableOpacity>

In the above example, the accessibilityLabel on the TouchableOpacity element would default to "Press me!". The label is constructed by concatenating all Text node children separated by spaces.

accessibilityTraits (iOS) #

Accessibility traits tell a person using VoiceOver what kind of element they have selected. Is this element a label? A button? A header? These questions are answered by accessibilityTraits.

To use, set the accessibilityTraits property to one of (or an array of) accessibility trait strings:

  • none Used when the element has no traits.
  • button Used when the element should be treated as a button.
  • link Used when the element should be treated as a link.
  • header Used when an element acts as a header for a content section (e.g. the title of a navigation bar).
  • search Used when the text field element should also be treated as a search field.
  • image Used when the element should be treated as an image. Can be combined with button or link, for example.
  • selected Used when the element is selected. For example, a selected row in a table or a selected button within a segmented control.
  • plays Used when the element plays its own sound when activated.
  • key Used when the element acts as a keyboard key.
  • text Used when the element should be treated as static text that cannot change.
  • summary Used when an element can be used to provide a quick summary of current conditions in the app when the app first launches. For example, when Weather first launches, the element with today's weather conditions is marked with this trait.
  • disabled Used when the control is not enabled and does not respond to user input.
  • frequentUpdates Used when the element frequently updates its label or value, but too often to send notifications. Allows an accessibility client to poll for changes. A stopwatch would be an example.
  • startsMedia Used when activating an element starts a media session (e.g. playing a movie, recording audio) that should not be interrupted by output from an assistive technology, like VoiceOver.
  • adjustable Used when an element can be "adjusted" (e.g. a slider).
  • allowsDirectInteraction Used when an element allows direct touch interaction for VoiceOver users (for example, a view representing a piano keyboard).
  • pageTurn Informs VoiceOver that it should scroll to the next page when it finishes reading the contents of the element.

onAccessibilityTap (iOS) #

Use this property to assign a custom function to be called when someone activates an accessible element by double tapping on it while it's selected.

onMagicTap (iOS) #

Assign this property to a custom function which will be called when someone performs the "magic tap" gesture, which is a double-tap with two fingers. A magic tap function should perform the most relevant action a user could take on a component. In the Phone app on iPhone, a magic tap answers a phone call, or ends the current one. If the selected element does not have an onMagicTap function, the system will traverse up the view hierarchy until it finds a view that does.

accessibilityComponentType (Android) #

In some cases, we also want to alert the end user of the type of selected component (i.e., that it is a “button”). If we were using native buttons, this would work automatically. Since we are using javascript, we need to provide a bit more context for TalkBack. To do so, you must specify the ‘accessibilityComponentType’ property for any UI component. For instances, we support ‘button’, ‘radiobutton_checked’ and ‘radiobutton_unchecked’ and so on.

<TouchableWithoutFeedback accessibilityComponentType=”button” onPress={this._onPress}> <View style={styles.button}> <Text style={styles.buttonText}>Press me!</Text> </View> -</TouchableWithoutFeedback>

In the above example, the TouchableWithoutFeedback is being announced by TalkBack as a native Button.

accessibilityLiveRegion (Android) #

When components dynamically change, we want TalkBack to alert the end user. This is made possible by the ‘accessibilityLiveRegion’ property. It can be set to ‘none’, ‘polite’ and ‘assertive’:

  • none Accessibility services should not announce changes to this view.
  • polite Accessibility services should announce changes to this view.
  • assertive Accessibility services should interrupt ongoing speech to immediately announce changes to this view.
<TouchableWithoutFeedback onPress={this._addOne}> +</TouchableWithoutFeedback>

In the above example, the TouchableWithoutFeedback is being announced by TalkBack as a native Button.

accessibilityLiveRegion (Android) #

When components dynamically change, we want TalkBack to alert the end user. This is made possible by the ‘accessibilityLiveRegion’ property. It can be set to ‘none’, ‘polite’ and ‘assertive’:

  • none Accessibility services should not announce changes to this view.
  • polite Accessibility services should announce changes to this view.
  • assertive Accessibility services should interrupt ongoing speech to immediately announce changes to this view.
<TouchableWithoutFeedback onPress={this._addOne}> <View style={styles.embedded}> <Text>Click me</Text> </View> </TouchableWithoutFeedback> <Text accessibilityLiveRegion="polite"> Clicked {this.state.count} times -</Text>

In the above example method _addOne changes the state.count variable. As soon as an end user clicks the TouchableWithoutFeedback, TalkBack reads text in the Text view because of its 'accessibilityLiveRegion=”polite”' property.

importantForAccessibility (Android) #

In the case of two overlapping UI components with the same parent, default accessibility focus can have unpredictable behavior. The ‘importantForAccessibility’ property will resolve this by controlling if a view fires accessibility events and if it is reported to accessibility services. It can be set to ‘auto’, ‘yes’, ‘no’ and ‘no-hide-descendants’ (the last value will force accessibility services to ignore the component and all of its children).

<View style={styles.container}> +</Text>

In the above example method _addOne changes the state.count variable. As soon as an end user clicks the TouchableWithoutFeedback, TalkBack reads text in the Text view because of its 'accessibilityLiveRegion=”polite”' property.

importantForAccessibility (Android) #

In the case of two overlapping UI components with the same parent, default accessibility focus can have unpredictable behavior. The ‘importantForAccessibility’ property will resolve this by controlling if a view fires accessibility events and if it is reported to accessibility services. It can be set to ‘auto’, ‘yes’, ‘no’ and ‘no-hide-descendants’ (the last value will force accessibility services to ignore the component and all of its children).

<View style={styles.container}> <View style={{position: 'absolute', left: 10, top: 10, right: 10, height: 100, backgroundColor: 'green'}} importantForAccessibility=”yes”> <Text> First layout </Text> @@ -26,7 +26,7 @@ backgroundColor: 'yellow'}} importantForAccessibility=”no-hide-descendant”> <Text> Second layout </Text> </View> -</View>

In the above example, the yellow layout and its descendants are completely invisible to TalkBack and all other accessibility services. So we can easily use overlapping views with the same parent without confusing TalkBack.

Sending Accessibility Events (Android) #

Sometimes it is useful to trigger an accessibility event on a UI component (i.e. when a custom view appears on a screen or a custom radio button has been selected). Native UIManager module exposes a method ‘sendAccessibilityEvent’ for this purpose. It takes two arguments: view tag and a type of an event.

_onPress: function() { +</View>

In the above example, the yellow layout and its descendants are completely invisible to TalkBack and all other accessibility services. So we can easily use overlapping views with the same parent without confusing TalkBack.

Sending Accessibility Events (Android) #

Sometimes it is useful to trigger an accessibility event on a UI component (i.e. when a custom view appears on a screen or a custom radio button has been selected). Native UIManager module exposes a method ‘sendAccessibilityEvent’ for this purpose. It takes two arguments: view tag and a type of an event.

_onPress: function() { this.state.radioButton = this.state.radioButton === “radiobutton_checked” ? “radiobutton_unchecked” : “radiobutton_checked”; if (this.state.radioButton === “radiobutton_checked”) { @@ -38,7 +38,7 @@ <CustomRadioButton accessibleComponentType={this.state.radioButton} - onPress={this._onPress}/>

In the above example we've created a custom radio button that now behaves like a native one. More specifically, TalkBack now correctly announces changes to the radio button selection.

Testing VoiceOver Support (iOS) #

To enable VoiceOver, go to the Settings app on your iOS device. Tap General, then Accessibility. There you will find many tools that people use to use to make their devices more usable, such as bolder text, increased contrast, and VoiceOver.

To enable VoiceOver, tap on VoiceOver under "Vision" and toggle the switch that appears at the top.

At the very bottom of the Accessibility settings, there is an "Accessibility Shortcut". You can use this to toggle VoiceOver by triple clicking the Home button.

© 2015 Facebook Inc.

ActionSheetIOS #

Edit on GitHub

Methods #

static showActionSheetWithOptions(options: Object, callback: Function) #

static showShareActionSheetWithOptions(options: Object, failureCallback: Function, successCallback: Function) #

Examples #

Edit on GitHub
'use strict'; +ActionSheetIOS – React Native | A framework for building native apps using React

ActionSheetIOS #

Edit on GitHub

Methods #

static showActionSheetWithOptions(options: Object, callback: Function) #

static showShareActionSheetWithOptions(options: Object, failureCallback: Function, successCallback: Function) #

Examples #

Edit on GitHub
'use strict'; var React = require('react-native'); var { @@ -150,7 +150,7 @@ exports.examples : 'Show Share Action Sheet', render(): ReactElement { return <ShareActionSheetExample />; } } -];
© 2015 Facebook Inc.

ActivityIndicatorIOS #

Edit on GitHub

Props #

animating bool #

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

color string #

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

hidesWhenStopped bool #

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

onLayout function #

Invoked on mount and layout changes with

{nativeEvent: { layout: {x, y, width, height}}}.

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

Size of the indicator. Small has a height of 20, large has a height of 36.

Examples #

Edit on GitHub
'use strict'; +ActivityIndicatorIOS – React Native | A framework for building native apps using React

ActivityIndicatorIOS #

Edit on GitHub

Props #

animating bool #

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

color string #

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

hidesWhenStopped bool #

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

onLayout function #

Invoked on mount and layout changes with

{nativeEvent: { layout: {x, y, width, height}}}.

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

Size of the indicator. Small has a height of 20, large has a height of 36.

Examples #

Edit on GitHub
'use strict'; var React = require('react-native'); var { @@ -144,7 +144,7 @@ exports.examples : 'row', justifyContent: 'space-around', }, -});
© 2015 Facebook Inc.

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, -see AlertIOS; entering text in an alert is common on iOS only.

iOS #

On iOS you can specify any number of buttons. Each button can optionally -specify a style, which is one of 'default', 'cancel' or 'destructive'.

Android #

On Android at most three buttons can be specified. Android has a concept +see AlertIOS; entering text in an alert is common on iOS only.

iOS #

On iOS you can specify any number of buttons. Each button can optionally +specify a style, which is one of 'default', 'cancel' or 'destructive'.

Android #

On Android at most three buttons can be specified. Android has a concept of a neutral, negative and a positive button:

  • If you specify one button, it will be the 'positive' one (such as 'OK')
  • Two buttons mean 'negative', 'positive' (such as 'Cancel', 'OK')
  • Three buttons mean 'neutral', 'negative', 'positive' (such as 'Later', 'Cancel', 'OK')
// Works on both iOS and Android Alert.alert( 'Alert Title', @@ -13,7 +13,7 @@ of a neutral, negative and a positive button:

  • If you specify one butt {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'}, {text: 'OK', onPress: () => console.log('OK Pressed')}, ] -)

Methods #

static alert(title: string, message?: string, buttons?: Buttons, type?: AlertType) #

Examples #

Edit on GitHub
'use strict'; +)

Methods #

static alert(title: string, message?: string, buttons?: Buttons, type?: AlertType) #

Examples #

Edit on GitHub
'use strict'; var React = require('react-native'); var { @@ -133,7 +133,7 @@ of a neutral, negative and a positive button:

  • If you specify one butt module.exports = { AlertExample, SimpleAlertExampleBlock, -};
© 2015 Facebook Inc.

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 -alert popup.

Methods #

static alert(title: string, message?: string, callbackOrButtons?: ?(() => void) | ButtonsArray, type?: AlertType) #

Creates a popup to alert the user. See +alert popup.

Methods #

static alert(title: string, message?: string, callbackOrButtons?: ?(() => void) | ButtonsArray, type?: AlertType) #

Creates a popup to alert the user. See Alert.

  • title: string -- The dialog's title.
  • message: string -- An optional message that appears above the text input.
  • callbackOrButtons -- This optional argument should be either a single-argument function or an array of buttons. If passed a function, it will be called when the user taps 'OK'.

    If passed an array of button configurations, each button should include @@ -10,7 +10,7 @@ a text key, as well as optional onPress and styl style should be one of 'default', 'cancel' or 'destructive'.

  • type -- deprecated, do not use

Example:

AlertIOS.alert( 'Sync Complete', 'All your data are belong to us.' -);

static prompt(title: string, message?: string, callbackOrButtons?: ?((text: string) => void) | ButtonsArray, type?: AlertType, defaultValue?: string) #

Prompt the user to enter some text.

  • title: string -- The dialog's title.
  • message: string -- An optional message that appears above the text input.
  • callbackOrButtons -- This optional argument should be either a +);

static prompt(title: string, message?: string, callbackOrButtons?: ?((text: string) => void) | ButtonsArray, type?: AlertType, defaultValue?: string) #

Prompt the user to enter some text.

  • title: string -- The dialog's title.
  • message: string -- An optional message that appears above the text input.
  • callbackOrButtons -- This optional argument should be either a single-argument function or an array of buttons. If passed a function, it will be called with the prompt's value when the user taps 'OK'.

    If passed an array of button configurations, each button should include a text key, as well as optional onPress and style keys (see example). @@ -29,7 +29,7 @@ a text key, as well as optional onPress and styl text => console.log("Your username is "+text), null, 'default' -)

Examples #

Edit on GitHub
'use strict'; +)

Examples #

Edit on GitHub
'use strict'; var React = require('react-native'); var { @@ -187,7 +187,7 @@ class PromptOptions extends : '#eeeeee', padding: 10, }, -});
© 2015 Facebook Inc.

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. Android Support Repository >= 17 (for Android Support Library)
  4. Android NDK (download & extraction instructions here)

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. Android Support Repository >= 17 (for Android Support Library)
  4. Android NDK (download & extraction instructions here)

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

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:

... +ndk.dir=/Users/your_unix_name/android-ndk/android-ndk-r10e

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 { classpath 'com.android.tools.build:gradle:1.3.1' classpath 'de.undercouch:gradle-download-task:2.0.0' @@ -8,7 +8,7 @@ ndk.dir= // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } -...

3. Adding the :ReactAndroid project #

Add the :ReactAndroid project in android/settings.gradle:

... +...

3. Adding the :ReactAndroid project #

Add the :ReactAndroid project in android/settings.gradle:

... include ':ReactAndroid' project(':ReactAndroid').projectDir = new File( @@ -22,13 +22,13 @@ dependencies { ... } -...

4. Making 3rd-party modules use your fork #

If you use 3rd-party React Native modules, you need to override their dependencies so that they don't bundle the pre-compiled library. Otherwise you'll get an error while compiling - Error: more than one library with package name 'com.facebook.react'.

Modify your android/app/build.gradle and replace compile project(':react-native-custom-module') with:

compile(project(':react-native-custom-module')) { +...

4. Making 3rd-party modules use your fork #

If you use 3rd-party React Native modules, you need to override their dependencies so that they don't bundle the pre-compiled library. Otherwise you'll get an error while compiling - Error: more than one library with package name 'com.facebook.react'.

Modify your android/app/build.gradle and replace compile project(':react-native-custom-module') with:

compile(project(':react-native-custom-module')) { exclude group: 'com.facebook.react', module: 'react-native' -}

Additional notes #

Building from source can take a long time, especially for the first build, as it needs to download ~200 MB of artifacts and compile the native code. Every time you update the react-native version from your repo, the build directory may get deleted, and all the files are re-downloaded. To avoid this, you might want to change your build directory path by editing the ~/.gradle/init.gradle file:

gradle.projectsLoaded { +}

Additional notes #

Building from source can take a long time, especially for the first build, as it needs to download ~200 MB of artifacts and compile the native code. Every time you update the react-native version from your repo, the build directory may get deleted, and all the files are re-downloaded. To avoid this, you might want to change your build directory path by editing the ~/.gradle/init.gradle file:

gradle.projectsLoaded { rootProject.allprojects { buildDir = "/path/to/build/directory/${rootProject.name}/${project.name}" } -}
© 2015 Facebook Inc.

Android Setup #

Edit on GitHub

This guide describes basic steps of the Android development environment setup that are required to run React Native android apps on an android emulator. We don't discuss developer tool configuration such as IDEs here.

Install Git #

  • On Mac, if you have installed XCode, Git is already installed, otherwise run the following:

    brew install git
  • On Linux, install Git via your package manager.

  • On Windows, download and install Git for Windows. During the setup process, choose "Run Git from Windows Command Prompt", which will add Git to your PATH environment variable.

Install the Android SDK (unless you have it) #

  1. Install the latest JDK
  2. Install the Android SDK:

Define the ANDROID_HOME environment variable #

IMPORTANT: Make sure the ANDROID_HOME environment variable points to your existing Android SDK:

  • On Mac, add this to your ~/.bashrc, ~/.bash_profile or whatever your shell uses:

    # If you installed the SDK via Homebrew, otherwise ~/Library/Android/sdk -export ANDROID_HOME=/usr/local/opt/android-sdk
  • On Linux, add this to your ~/.bashrc, ~/.bash_profile or whatever your shell uses:

    export ANDROID_HOME=<path_where_you_unpacked_android_sdk>
  • On Windows, go to Control Panel -> System and Security -> System -> Change settings -> Advanced -> Environment variables -> New

NOTE: You need to restart the Command Prompt (Windows) / Terminal Emulator (Mac OS X, Linux) to apply the new Environment variables.

Use gradle daemon #

React Native Android use gradle as a build system. We recommend to enable gradle daemon functionality which may result in up to 50% improvement in incremental build times for changes in java code. Learn here how to enable it for your platform.

Configure your SDK #

  1. Open the Android SDK Manager (on Mac start a new shell and run android); in the window that appears make sure you check:
    • Android SDK Build-tools version 23.0.1
    • Android 6.0 (API 23)
    • Android Support Repository
  2. Click "Install Packages"

SDK Manager window SDK Manager window

Install Genymotion #

Genymotion is much easier to set up than stock Google emulators. However, it's only free for personal use. If you want to use the stock Google emulator, see below.

  1. Download and install Genymotion.
  2. Open Genymotion. It might ask you to install VirtualBox unless you already have it.
  3. Create a new emulator and start it.
  4. To bring up the developer menu press ⌘+M

Alternative: Create a stock Google emulator #

  1. Start a new shell and run android; in the window that appears make sure you check:
    • Intel x86 Atom System Image (for Android 5.1.1 - API 22)
    • Intel x86 Emulator Accelerator (HAXM installer)
  2. Click "Install Packages".
  3. Configure hardware acceleration (HAXM), otherwise the emulator is going to be slow.
  4. Create an Android Virtual Device (AVD):
    1. Run android avd and click on Create... -Create AVD dialog
    2. With the new AVD selected, click Start...
  5. To bring up the developer menu press F2 (or install Frappé)

Windows Hyper-V Alternative #

The Visual Studio Emulator for Android is a free android emulator that is hardware accelerated via Hyper-V. It doesn't require you to install Visual Studio at all.

To use it with react-native you just have to add a key and value to your registry:

  1. Open the Run Command (Windows+R)
  2. Enter regedit.exe
  3. In the Registry Editor navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Android SDK Tools
  4. Right Click on Android SDK Tools and choose New > String Value
  5. Set the name to Path
  6. Double Click the new Path Key and set the value to C:\Program Files\Android\sdk. The path value might be different on your machine.

You will also need to run the command adb reverse tcp:8081 tcp:8081 with this emulator.

Then restart the emulator and when it runs you can just do react-native run-android as usual.

© 2015 Facebook Inc.

Android Setup #

Edit on GitHub

This guide describes basic steps of the Android development environment setup that are required to run React Native android apps on an android emulator.

Install Git #

  • On Mac, if you have installed XCode, Git is already installed, otherwise run the following:

    brew install git
  • On Linux, install Git via your package manager.

  • On Windows, download and install Git for Windows. During the setup process, choose "Run Git from Windows Command Prompt", which will add Git to your PATH environment variable.

Install the Android SDK (unless you already have it) #

  1. Install the latest JDK
  2. Install the Android SDK:

Define the ANDROID_HOME environment variable #

IMPORTANT: Make sure the ANDROID_HOME environment variable points to your existing Android SDK:

  • On Mac, add this to your ~/.bashrc, ~/.bash_profile or whatever your shell uses:

    # If you installed the SDK via Homebrew, otherwise ~/Library/Android/sdk +export ANDROID_HOME=/usr/local/opt/android-sdk
  • On Linux, add this to your ~/.bashrc, ~/.bash_profile or whatever your shell uses:

    export ANDROID_HOME=<path_where_you_unpacked_android_sdk>
  • On Windows, go to Control Panel -> System and Security -> System -> Change settings -> Advanced -> Environment variables -> New

NOTE: You need to restart the Command Prompt (Windows) / Terminal Emulator (Mac OS X, Linux) to apply the new Environment variables.

Use gradle daemon #

React Native Android use gradle as a build system. We recommend to enable gradle daemon functionality which may result in up to 50% improvement in incremental build times for changes in java code. Learn here how to enable it for your platform.

Configure your SDK #

  1. Open the Android SDK Manager (on Mac start a new shell and run android); in the window that appears make sure you check:
    • Android SDK Build-tools version 23.0.1
    • Android 6.0 (API 23)
    • Android Support Repository
  2. Click "Install Packages"

SDK Manager window SDK Manager window

Install Genymotion #

Genymotion is much easier to set up than stock Google emulators. However, it's only free for personal use. If you want to use the stock Google emulator, see below.

  1. Download and install Genymotion.
  2. Open Genymotion. It might ask you to install VirtualBox unless you already have it.
  3. Create a new emulator and start it.
  4. To bring up the developer menu press ⌘+M

Alternative: Create a stock Google emulator #

  1. Start a new shell and run android; in the window that appears make sure you check:
    • Intel x86 Atom System Image (for Android 5.1.1 - API 22)
    • Intel x86 Emulator Accelerator (HAXM installer)
  2. Click "Install Packages".
  3. Configure hardware acceleration (HAXM), otherwise the emulator is going to be slow.
  4. Create an Android Virtual Device (AVD):
    1. Run android avd and click on Create... +Create AVD dialog
    2. With the new AVD selected, click Start...
  5. To bring up the developer menu press F2 (or install Frappé)

Windows Hyper-V Alternative #

The Visual Studio Emulator for Android is a free android emulator that is hardware accelerated via Hyper-V. It doesn't require you to install Visual Studio at all.

To use it with react-native you just have to add a key and value to your registry:

  1. Open the Run Command (Windows+R)
  2. Enter regedit.exe
  3. In the Registry Editor navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Android SDK Tools
  4. Right Click on Android SDK Tools and choose New > String Value
  5. Set the name to Path
  6. Double Click the new Path Key and set the value to C:\Program Files\Android\sdk. The path value might be different on your machine.

You will also need to run the command adb reverse tcp:8081 tcp:8081 with this emulator.

Then restart the emulator and when it runs you can just do react-native run-android as usual.

Editing your app's Java code in Android Studio #

You can use any editor to edit JavaScript. If you want to use Android Studio to work on native code, from the Welcome screen of Android Studio choose "Import project" and select the android folder of your app.

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

© 2015 Facebook Inc.

Profiling Android UI Performance #

Edit on GitHub

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

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

Make sure that JS dev mode is OFF!

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

Profiling with Systrace #

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

Collecting a trace #

NOTE:

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

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

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

A quick breakdown of this command:

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

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

Reading the trace #

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

Example

HINT: Use the WASD keys to strafe and zoom

Enable VSync highlighting #

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

Enable VSync Highlighting

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

Find your process #

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

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

UI Thread #

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

UI Thread Example

JS Thread #

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

JS Thread Example

Native Modules Thread #

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

Native Modules Thread Example

Bonus: Render Thread #

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

Render Thread Example

Identifying a culprit #

A smooth animation should look something like the following:

Smooth Animation

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

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

Choppy Animation from JS

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

You might also see something like this:

Choppy Animation from UI

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

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

JS Issues #

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

Too much JS

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

TODO: Add more tools for profiling JS

Native UI Issues #

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

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

Too much GPU work #

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

Overloaded GPU

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

To mitigate this, you should:

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

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

Creating new views on the UI thread #

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

Creating Views

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

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

Still stuck? #

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

© 2016 Facebook Inc.

Animated #

Edit on GitHub

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

Animated #

Edit on GitHub

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

The simplest workflow is to create an Animated.Value, hook it up to one or more style attributes of an animated component, and then drive updates either @@ -58,17 +58,17 @@ event loop. This does influence the API, so keep that in mind when it seems a little trickier to do something compared to a fully synchronous system. Checkout Animated.Value.addListener as a way to work around some of these limitations, but use it sparingly since it might have performance -implications in the future.

Methods #

static decay(value: AnimatedValue | AnimatedValueXY, config: DecayAnimationConfig) #

Animates a value from an initial velocity to zero based on a decay -coefficient.

static timing(value: AnimatedValue | AnimatedValueXY, config: TimingAnimationConfig) #

Animates a value along a timed easing curve. The Easing module has tons -of pre-defined curves, or you can use your own function.

static spring(value: AnimatedValue | AnimatedValueXY, config: SpringAnimationConfig) #

Spring animation based on Rebound and Origami. Tracks velocity state to -create fluid motions as the toValue updates, and can be chained together.

static add(a: Animated, b: Animated) #

Creates a new Animated value composed from two Animated values added -together.

static multiply(a: Animated, b: Animated) #

Creates a new Animated value composed from two Animated values multiplied -together.

static delay(time: number) #

Starts an animation after the given delay.

static sequence(animations: Array<CompositeAnimation>) #

Starts an array of animations in order, waiting for each to complete +implications in the future.

Methods #

static decay(value: AnimatedValue | AnimatedValueXY, config: DecayAnimationConfig) #

Animates a value from an initial velocity to zero based on a decay +coefficient.

static timing(value: AnimatedValue | AnimatedValueXY, config: TimingAnimationConfig) #

Animates a value along a timed easing curve. The Easing module has tons +of pre-defined curves, or you can use your own function.

static spring(value: AnimatedValue | AnimatedValueXY, config: SpringAnimationConfig) #

Spring animation based on Rebound and Origami. Tracks velocity state to +create fluid motions as the toValue updates, and can be chained together.

static add(a: Animated, b: Animated) #

Creates a new Animated value composed from two Animated values added +together.

static multiply(a: Animated, b: Animated) #

Creates a new Animated value composed from two Animated values multiplied +together.

static delay(time: number) #

Starts an animation after the given delay.

static sequence(animations: Array<CompositeAnimation>) #

Starts an array of animations in order, waiting for each to complete before starting the next. If the current running animation is stopped, no -following animations will be started.

static parallel(animations: Array<CompositeAnimation>, config?: ParallelConfig) #

Starts an array of animations all at the same time. By default, if one +following animations will be started.

static parallel(animations: Array<CompositeAnimation>, config?: ParallelConfig) #

Starts an array of animations all at the same time. By default, if one of the animations is stopped, they will all be stopped. You can override -this with the stopTogether flag.

static stagger(time: number, animations: Array<CompositeAnimation>) #

Array of animations may run in parallel (overlap), but are started in -sequence with successive delays. Nice for doing trailing effects.

static event(argMapping: Array<Mapping>, config?: EventConfig) #

Takes an array of mappings and extracts values from each arg accordingly, +this with the stopTogether flag.

static stagger(time: number, animations: Array<CompositeAnimation>) #

Array of animations may run in parallel (overlap), but are started in +sequence with successive delays. Nice for doing trailing effects.

static event(argMapping: Array<Mapping>, config?: EventConfig) #

Takes an array of mappings and extracts values from each arg accordingly, then calls setValue on the mapped outputs. e.g.

onScroll={Animated.event( [{nativeEvent: {contentOffset: {x: this._scrollX}}}] {listener}, // Optional async listener @@ -77,21 +77,21 @@ sequence with successive delays. Nice for doing trailing effects.

: Animated.event([ null, // raw event arg ignored {dx: this._panX}, // gestureState arg - ]),

static createAnimatedComponent(Component: any) #

Make any React component Animatable. Used to create Animated.View, etc.

Properties #

Value: AnimatedValue #

Standard value class for driving animations. Typically initialized with -new Animated.Value(0);

ValueXY: AnimatedValueXY #

2D value class for driving 2D animations, such as pan gestures.

class AnimatedValue #

    Standard value for driving animations. One Animated.Value can drive + ]),

static createAnimatedComponent(Component: any) #

Make any React component Animatable. Used to create Animated.View, etc.

Properties #

Value: AnimatedValue #

Standard value class for driving animations. Typically initialized with +new Animated.Value(0);

ValueXY: AnimatedValueXY #

2D value class for driving 2D animations, such as pan gestures.

class AnimatedValue #

    Standard value for driving animations. One Animated.Value can drive multiple properties in a synchronized fashion, but can only be driven by one mechanism at a time. Using a new mechanism (e.g. starting a new animation, -or calling setValue) will stop any previous ones.

    Methods #

    constructor(value: number) #

    setValue(value: number) #

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

    setOffset(offset: number) #

    Sets an offset that is applied on top of whatever value is set, whether via +or calling setValue) will stop any previous ones.

    Methods #

    constructor(value: number) #

    setValue(value: number) #

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

    setOffset(offset: number) #

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

    flattenOffset() #

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

    addListener(callback: ValueListenerCallback) #

    Adds an asynchronous listener to the value so you can observe updates from +things like the start of a pan gesture.

    flattenOffset() #

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

    addListener(callback: ValueListenerCallback) #

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

    removeListener(id: string) #

    removeAllListeners() #

    stopAnimation(callback?: ?(value: number) => void) #

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

    removeListener(id: string) #

    removeAllListeners() #

    stopAnimation(callback?: ?(value: number) => void) #

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

    interpolate(config: InterpolationConfigType) #

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

    animate(animation: Animation, callback: EndCallback) #

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

    stopTracking() #

    Typically only used internally.

    track(tracking: Animated) #

    Typically only used internally.

class AnimatedValueXY #

    2D Value for driving 2D animations, such as pan gestures. Almost identical +state to match the animation position with layout.

interpolate(config: InterpolationConfigType) #

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

animate(animation: Animation, callback: EndCallback) #

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

stopTracking() #

Typically only used internally.

track(tracking: Animated) #

Typically only used internally.

class AnimatedValueXY #

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

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

    Methods #

    constructor(valueIn?: ?{x: number | AnimatedValue; y: number | AnimatedValue}) #

    setValue(value: {x: number; y: number}) #

    setOffset(offset: {x: number; y: number}) #

    flattenOffset() #

    stopAnimation(callback?: ?() => number) #

    addListener(callback: ValueXYListenerCallback) #

    removeListener(id: string) #

    getLayout() #

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

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

    getTranslateTransform() #

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

    style={{ + }

    Methods #

    constructor(valueIn?: ?{x: number | AnimatedValue; y: number | AnimatedValue}) #

    setValue(value: {x: number; y: number}) #

    setOffset(offset: {x: number; y: number}) #

    flattenOffset() #

    stopAnimation(callback?: ?() => number) #

    addListener(callback: ValueXYListenerCallback) #

    removeListener(id: string) #

    getLayout() #

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

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

    getTranslateTransform() #

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

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

Examples #

Edit on GitHub
'use strict'; + }}

Examples #

Edit on GitHub
'use strict'; var React = require('react-native'); var { @@ -339,7 +339,7 @@ exports.examples : 10, alignItems: 'center', }, -});
© 2015 Facebook Inc.

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 -more granular and interactive control of specific values.

Animated #

The Animated library is designed to make it very easy to concisely express a +more granular and interactive control of specific values.

Animated #

The Animated library is designed to make it very easy to concisely express a wide variety of interesting animation and interaction patterns in a very performant way. Animated focuses on declarative relationships between inputs and outputs, with configurable transforms in between, and simple start/stop @@ -45,7 +45,7 @@ all of its dependent mappings on each frame as the spring animates (in this case, just the scale). This is done in an optimized way that is faster than calling setState and re-rendering. Because the entire configuration is declarative, we will be able to implement further optimizations that serialize -the configuration and runs the animation on a high-priority thread.

Core API #

Most everything you need hangs directly off the Animated module. This +the configuration and runs the animation on a high-priority thread.

Core API #

Most everything you need hangs directly off the Animated module. This includes two value types, Value for single values and ValueXY for vectors, three animation types, spring, decay, and timing, and three component types, View, Text, and Image. You can make any other component animated with @@ -56,7 +56,7 @@ that will be called when the animation is done. If the animation is done because it finished running normally, the completion callback will be invoked with {finished: true}, but if the animation is done because stop was called on it before it could finish (e.g. because it was interrupted by a gesture or -another animation), then it will receive {finished: false}.

Composing Animations #

Animations can also be composed with parallel, sequence, stagger, and +another animation), then it will receive {finished: false}.

Composing Animations #

Animations can also be composed with parallel, sequence, stagger, and delay, each of which simply take an array of animations to execute and automatically calls start/stop as appropriate. For example:

Animated.sequence([ // spring to start and twirl after decay finishes Animated.decay(position, { // coast to a stop @@ -73,7 +73,7 @@ automatically calls start/stop as appropriate. For example:

]), ]).start(); // start the sequence group

By default, if one animation is stopped or interrupted, then all other animations in the group are also stopped. Parallel has a stopTogether option -that can be set to false to disable this.

Interpolation #

Another powerful part of the Animated API is the interpolate function. It +that can be set to false to disable this.

Interpolation #

Another powerful part of the Animated API is the interpolate function. It allows input ranges to map to different output ranges. For example, a simple mapping to convert a 0-1 range to a 0-100 range would be

value.interpolate({ inputRange: [0, 1], @@ -93,7 +93,7 @@ like step and bounce. interpolation also has configurable behavior extrapolating the outputRange. You can set the extrapolation by setting the extrapolate, extrapolateLeft or extrapolateRight options. The default value is extend but you can use clamp to prevent the output value from exceeding -outputRange.

Tracking Dynamic Values #

Animated values can also track other values. Just set the toValue of an +outputRange.

Tracking Dynamic Values #

Animated values can also track other values. Just set the toValue of an animation to another animated value instead of a plain number, for example with spring physics for an interaction like "Chat Heads", or via timing with duration: 0 for rigid/instant tracking. They can also be composed with @@ -108,7 +108,7 @@ It is a simple wrapper that basically just contains two Animated.ValueValueXY a drop-in replacement for Value in many cases. For example, in the code snippet above, leader and follower could both be of type ValueXY and the x -and y values will both track as you would expect.

Input Events #

Animated.event is the input side of the Animated API, allowing gestures and +and y values will both track as you would expect.

Input Events #

Animated.event is the input side of the Animated API, allowing gestures and other events to map directly to animated values. This is done with a structured map syntax so that values can be extracted from complex event objects. The first level is an array to allow mapping across multiple args, and that array @@ -124,7 +124,7 @@ onPanResponderMove= // extract dx and dy from gestureState // like 'pan.x = gestureState.dx, pan.y = gestureState.dy' {dx: pan.x, dy: pan.y} -]);

Responding to the Current Animation Value #

You may notice that there is no obvious way to read the current value while +]);

Responding to the Current Animation Value #

You may notice that there is no obvious way to read the current value while animating - this is because the value may only be known in the native runtime due to optimizations. If you need to run JavaScript in response to the current value, there are two approaches:

  • spring.stopAnimation(callback) will stop the animation and invoke callback @@ -132,14 +132,14 @@ with the final value - this is useful when making gesture transitions.
  • < animation is running, providing a recent value. This is useful for triggering state changes, for example snapping a bobble to a new option as the user drags it closer, because these larger state changes are less sensitive to a few frames -of lag compared to continuous gestures like panning which need to run at 60fps.

Future Work #

As previously mentioned, we're planning on optimizing Animated under the hood to +of lag compared to continuous gestures like panning which need to run at 60fps.

Future Work #

As previously mentioned, we're planning on optimizing Animated under the hood to make it even more performant. We would also like to experiment with more declarative and higher level gestures and triggers, such as horizontal vs. vertical panning.

The above API gives a powerful tool for expressing all sorts of animations in a concise, robust, and performant way. Check out more example code in UIExplorer/AnimationExample. Of course there may still be times where Animated doesn't support what you need, and the following sections cover other animation -systems.

LayoutAnimation #

LayoutAnimation allows you to globally configure create and update +systems.

LayoutAnimation #

LayoutAnimation allows you to globally configure create and update animations that will be used for all views in the next render/layout cycle. This is useful for doing flexbox layout updates without bothering to measure or calculate specific properties in order to animate them directly, and is @@ -179,12 +179,12 @@ what you want.

} });

Run this example

This example uses a preset value, you can customize the animations as you need, see LayoutAnimation.js -for more information.

requestAnimationFrame #

requestAnimationFrame is a polyfill from the browser that you might be +for more information.

requestAnimationFrame #

requestAnimationFrame is a polyfill from the browser that you might be familiar with. It accepts a function as its only argument and calls that function before the next repaint. It is an essential building block for animations that underlies all of the JavaScript-based animation APIs. In general, you shouldn't need to call this yourself - the animation APIs will -manage frame updates for you.

react-tween-state (Not recommended - use Animated instead) #

react-tween-state is a +manage frame updates for you.

react-tween-state (Not recommended - use Animated instead) #

react-tween-state is a minimal library that does exactly what its name suggests: it tweens a value in a component's state, starting at a from value and ending at a to value. This means that it generates the values in between those @@ -200,7 +200,7 @@ Linear easing often looks awkward and unnatural, so react-tween-state provides a selection of popular easing functions that can be applied to make your animations more pleasing.

This library does not ship with React Native - in order to use it on your project, you will need to install it with npm i react-tween-state ---save from your project directory.

var tweenState = require('react-tween-state'); +--save from your project directory.

import tweenState from 'react-tween-state'; var App = React.createClass({ mixins: [tweenState.Mixin], @@ -230,7 +230,7 @@ your project, you will need to install it with npm i react-tween-state }, });

Run this example

Here we animated the opacity, but as you might guess, we can animate any numeric value. Read more about react-tween-state in its -README.

Rebound (Not recommended - use Animated instead) #

Rebound.js is a JavaScript port of +README.

Rebound (Not recommended - use Animated instead) #

Rebound.js is a JavaScript port of Rebound for Android. It is similar in concept to react-tween-state: you have an initial value and set an end value, then Rebound generates intermediate values that you can @@ -241,7 +241,7 @@ value and end value. Rebound

Notice that Rebound animations can be interrupted - if you release in the middle of a press, it will animate back from the current state to -the original value.

var rebound = require('rebound'); +the original value.

import rebound from 'rebound'; var App = React.createClass({ // First we initialize the spring and add a listener, which calls @@ -296,7 +296,7 @@ oscillate around the end value. In the above example, we would add See the below gif for an example of where in your interface you might use this.

Screenshot from react-native-scrollable-tab-view. -You can run a similar example here.

A sidenote about setNativeProps #

As mentioned in the Direction Manipulation section, +You can run a similar example here.

A sidenote about setNativeProps #

As mentioned in the Direction Manipulation section, setNativeProps allows us to modify properties of native-backed components (components that are actually backed by native views, unlike composite components) directly, without having to setState and @@ -336,15 +336,14 @@ computationally intensive work until after animations are complete, using the InteractionManager. You can monitor the frame rate by using the In-App Developer Menu "FPS -Monitor" tool.

Navigator Scene Transitions #

As mentioned in the Navigator +Monitor" tool.

Navigator Scene Transitions #

As mentioned in the Navigator Comparison, Navigator is implemented in JavaScript and NavigatorIOS is a wrapper around native functionality provided by UINavigationController, so these scene transitions apply only to Navigator. In order to re-create the various animations provided by UINavigationController and also make them customizable, React Native exposes a -NavigatorSceneConfigs API.

var React = require('react-native'); -var { Dimensions } = React; +NavigatorSceneConfigs API.

import { Dimensions } from 'react-native'; var SCREEN_WIDTH = Dimensions.get('window').width; var BaseConfig = Navigator.SceneConfigs.FloatFromRight; @@ -366,7 +365,7 @@ make them customizable, React Native exposes a pop: CustomLeftToRightGesture, } });

Run this example

For further information about customizing scene transitions, read the -source.

© 2015 Facebook Inc.

AppRegistry #

Edit on GitHub

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

AppRegistry #

Edit on GitHub

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

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

Methods #

static registerConfig(config: Array<AppConfig>) #

static registerComponent(appKey: string, getComponentFunc: ComponentProvider) #

static registerRunnable(appKey: string, func: Function) #

static getAppKeys() #

static runApplication(appKey: string, appParameters: any) #

static unmountApplicationComponentAtRootTag(rootTag: number) #

© 2015 Facebook Inc.

AppState #

Edit on GitHub

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

AppState #

Edit on GitHub

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

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

App States #

  • active - The app is running in the foreground
  • background - The app is running in the background. The user is either +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 transition state that currently never happens for typical React Native apps.

    For more information, see -Apple's documentation

    Basic Usage #

    To see the current state, you can check AppState.currentState, which +Apple's documentation

    Basic Usage #

    To see the current state, you can check AppState.currentState, which will be kept up-to-date. However, currentState will be null at launch while AppState retrieves it over the bridge.

    getInitialState: function() { return { @@ -25,8 +25,8 @@ render: funct ); },

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

Methods #

static addEventListener(type: string, handler: Function) #

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

static removeEventListener(type: string, handler: Function) #

Remove a handler by passing the change event type and the handler

Properties #

currentState: TypeCastExpression #

Examples #

Edit on GitHub
'use strict'; +state will happen only momentarily.

Methods #

static addEventListener(type: string, handler: Function) #

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

static removeEventListener(type: string, handler: Function) #

Remove a handler by passing the change event type and the handler

Properties #

currentState: TypeCastExpression #

Examples #

Edit on GitHub
'use strict'; var React = require('react-native'); var { @@ -89,7 +89,7 @@ exports.examples : 'Previous states:', render(): ReactElement { return <AppStateSubscription showCurrentOnly={false} />; } }, -];
© 2015 Facebook Inc.

AppStateIOS #

Edit on GitHub

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

AppStateIOS #

Edit on GitHub

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

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

iOS App States #

  • active - The app is running in the foreground
  • background - The app is running in the background. The user is either +handling push notifications.

    iOS 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 transition state that currently never happens for typical React Native apps.

    For more information, see -Apple's documentation

    Basic Usage #

    To see the current state, you can check AppStateIOS.currentState, which +Apple's documentation

    Basic Usage #

    To see the current state, you can check AppStateIOS.currentState, which will be kept up-to-date. However, currentState will be null at launch while AppStateIOS retrieves it over the bridge.

    getInitialState: function() { return { @@ -25,11 +25,11 @@ render: funct ); },

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

Methods #

static addEventListener(type: string, handler: Function) #

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

static removeEventListener(type: string, handler: Function) #

Remove a handler by passing the change event type and the handler

Properties #

currentState: TypeCastExpression #

// TODO: getCurrentAppState callback seems to be called at a really late stage +state will happen only momentarily.

Methods #

static addEventListener(type: string, handler: Function) #

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

static removeEventListener(type: string, handler: Function) #

Remove a handler by passing the change event type and the handler

Properties #

currentState: TypeCastExpression #

// TODO: getCurrentAppState callback seems to be called at a really late stage // after app launch. Trying to get currentState when mounting App component // will likely to have the initial value here. -// Initialize to 'active' instead of null.

Examples #

Edit on GitHub
'use strict'; +// Initialize to 'active' instead of null.

Examples #

Edit on GitHub
'use strict'; var React = require('react-native'); var { @@ -110,7 +110,7 @@ exports.examples : 'In the simulator, hit Shift+Command+M to simulate a memory warning.', render(): ReactElement { return <AppStateSubscription showMemoryWarnings={true} />; } }, -];
© 2015 Facebook Inc.

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.

This JS code is a simple facade over the native iOS implementation to provide a clear JS API, real Error objects, and simple non-multi functions. Each -method returns a Promise object.

Methods #

static getItem(key: string, callback?: ?(error: ?Error, result: ?string) => void) #

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

static setItem(key: string, value: string, callback?: ?(error: ?Error) => void) #

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

static removeItem(key: string, callback?: ?(error: ?Error) => void) #

Returns a Promise object.

static mergeItem(key: string, value: string, callback?: ?(error: ?Error) => void) #

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

static clear(callback?: ?(error: ?Error) => void) #

Erases all AsyncStorage for all clients, libraries, etc. You probably +method returns a Promise object.

Methods #

static getItem(key: string, callback?: ?(error: ?Error, result: ?string) => void) #

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

static setItem(key: string, value: string, callback?: ?(error: ?Error) => void) #

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

static removeItem(key: string, callback?: ?(error: ?Error) => void) #

Returns a Promise object.

static mergeItem(key: string, value: string, callback?: ?(error: ?Error) => void) #

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

static clear(callback?: ?(error: ?Error) => void) #

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

static getAllKeys(callback?: ?(error: ?Error, keys: ?Array<string>) => void) #

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

static flushGetRequests() #

Flushes any pending requests using a single multiget

static multiGet(keys: Array<string>, callback?: ?(errors: ?Array<Error>, result: ?Array<Array<string>>) => void) #

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

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

static multiSet(keyValuePairs: Array<Array<string>>, callback?: ?(errors: ?Array<Error>) => void) #

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

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

static multiRemove(keys: Array<string>, callback?: ?(errors: ?Array<Error>) => void) #

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

static multiMerge(keyValuePairs: Array<Array<string>>, callback?: ?(errors: ?Array<Error>) => void) #

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

Not supported by all native implementations.

Properties #

Examples #

Edit on GitHub
'use strict'; +own keys instead. Returns a Promise object.

static getAllKeys(callback?: ?(error: ?Error, keys: ?Array<string>) => void) #

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

static flushGetRequests() #

Flushes any pending requests using a single multiget

static multiGet(keys: Array<string>, callback?: ?(errors: ?Array<Error>, result: ?Array<Array<string>>) => void) #

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

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

static multiSet(keyValuePairs: Array<Array<string>>, callback?: ?(errors: ?Array<Error>) => void) #

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

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

static multiRemove(keys: Array<string>, callback?: ?(errors: ?Array<Error>) => void) #

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

static multiMerge(keyValuePairs: Array<Array<string>>, callback?: ?(errors: ?Array<Error>) => void) #

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

Not supported by all native implementations.

Properties #

Examples #

Edit on GitHub
'use strict'; var React = require('react-native'); var { @@ -114,7 +114,7 @@ exports.examples : 'Basics - getItem, setItem, removeItem', render(): ReactElement { return <BasicStorageExample />; } }, -];
© 2015 Facebook Inc.

BackAndroid #

Edit on GitHub

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

BackAndroid #

Edit on GitHub

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

Example:

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

Methods #

static exitApp() #

static addEventListener(eventName: BackPressEventName, handler: Function) #

static removeEventListener(eventName: BackPressEventName, handler: Function) #

© 2015 Facebook Inc.

CameraRoll #

Edit on GitHub

CameraRoll provides access to the local camera roll / gallery.

Methods #

static saveImageWithTag(tag) #

Saves the image to the camera roll / gallery.

On Android, the tag is a local URI, such as "file:///sdcard/img.png".

On iOS, the tag can be one of the following:

  • local URI
  • assets-library tag
  • a tag not matching any of the above, which means the image data will -be stored in memory (and consume memory as long as the process is alive)

Returns a Promise which when resolved will be passed the new URI.

static getPhotos(params: object) #

Returns a Promise with photo identifier objects from the local camera -roll of the device matching shape defined by getPhotosReturnChecker.

@param {object} params See getPhotosParamChecker.

Returns a Promise which when resolved will be of shape getPhotosReturnChecker.

Examples #

Edit on GitHub
'use strict'; +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) #

Saves the image to the camera roll / gallery.

On Android, the tag is a local URI, such as "file:///sdcard/img.png".

On iOS, the tag can be one of the following:

  • local URI
  • assets-library tag
  • a tag not matching any of the above, which means the image data will +be stored in memory (and consume memory as long as the process is alive)

Returns a Promise which when resolved will be passed the new URI.

static getPhotos(params: object) #

Returns a Promise with photo identifier objects from the local camera +roll of the device matching shape defined by getPhotosReturnChecker.

@param {object} params See getPhotosParamChecker.

Returns a Promise which when resolved will be of shape getPhotosReturnChecker.

Examples #

Edit on GitHub
'use strict'; const React = require('react-native'); const { @@ -125,7 +125,7 @@ exports.examples : 'Photos', render(): ReactElement { return <CameraRollExample />; } } -];
© 2015 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

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)
© 2015 Facebook Inc.

Colors #

Edit on GitHub

The following formats are supported:

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

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

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

Communication between native and React Native #

Edit on GitHub

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

Introduction #

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

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

Properties #

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

Passing properties from native to React Native #

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

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

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

Communication between native and React Native #

Edit on GitHub

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

Introduction #

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

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

Properties #

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

Passing properties from native to React Native #

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

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

NSArray *imageList = @[@"http://foo.com/bar1.png", @"http://foo.com/bar2.png"]; NSDictionary *props = @{@"images" : imageList}; @@ -7,11 +7,10 @@ RCTRootView *rootView :@"ImageBrowserApp" initialProperties:props];
'use strict'; -var React = require('react-native'); - var { +import React, { View, Image -} = React; +} from 'react-native'; class ImageBrowserApp extends React.Component { renderImage: function(imgURI) { @@ -32,8 +31,8 @@ React.AppRegistry"http://foo.com/bar4.png"]; rootView.appProperties = @{@"images" : imageList};

It is fine to update properties anytime. However, updates have to be performed on the main thread. You use the getter on any thread.

There is no way to update only a few properties at a time. We suggest that you build it into your own wrapper instead.

Note: -Currently, JS functions componentWillReceiveProps and componentWillUpdateProps of the top level RN component will not be called after a prop update. However, you can access the new props in componentWillMount function.

Passing properties from React Native to native #

The problem exposing properties of native components is covered in detail in this article. In short, export properties with RCT_CUSTOM_VIEW_PROPERTY macro in your custom native component, then just use them in React Native as if the component was an ordinary React Native component.

Limits of properties #

The main drawback of cross-language properties is that they do not support callbacks, which would allow us to handle bottom-up data bindings. Imagine you have a small RN view that you want to be removed from the native parent view as a result of a JS action. There is no way to do that with props, as the information would need to go bottom-up.

Although we have a flavor of cross-language callbacks (described here), these callbacks are not always the thing we need. The main problem is that they are not intended to be passed as properties. Rather, this mechanism allows us to trigger a native action from JS, and handle the result of that action in JS.

Other ways of cross-language interaction (events and native modules) #

As stated in the previous chapter, using properties comes with some limitations. Sometimes properties are not enough to drive the logic of our app and we need a solution that gives more flexibility. This chapter covers other communication techniques available in React Native. They can be used for internal communication (between JS and native layers in RN) as well as for external communication (between RN and the 'pure native' part of your app).

React Native enables you to perform cross-language function calls. You can execute custom native code from JS and vice versa. Unfortunately, depending on the side we are working on, we achieve the same goal in different ways. For native - we use events mechanism to schedule an execution of a handler function in JS, while for React Native we directly call methods exported by native modules.

Calling React Native functions from native (events) #

Events are described in detail in this article. Note that using events gives us no guarantees about execution time, as the event is handled on a separate thread.

Events are powerful, because they allow us to change React Native components without needing a reference to them. However, there are some pitfalls that you can fall into while using them:

  • As events can be sent from anywhere, they can introduce spaghetti-style dependencies into your project.
  • Events share namespace, which means that you may encounter some name collisions. Collisions will not be detected statically, what makes them hard to debug.
  • If you use several instances of the same React Native component and you want to distinguish them from the perspective of your event, you'll likely need to introduce some kind of identifiers and pass them along with events (you can use the native view's reactTag as an identifier).

The common pattern we use when embedding native in React Native is to make the native component's RCTViewManager a delegate for the views, sending events back to JavaScript via the bridge. This keeps related event calls in one place.

Calling native functions from React Native (native modules) #

Native modules are Objective-C classes that are available in JS. Typically one instance of each module is created per JS bridge. They can export arbitrary functions and constants to React Native. They have been covered in detail in this article.

The fact that native modules are singletons limits the mechanism in context of embedding. Let's say we have a React Native component embedded in a native view and we want to update the native, parent view. Using the native module mechanism, we would export a function that not only takes expected arguments, but also an identifier of the parent native view. The identifier would be used to retrieve a reference to the parent view to update. That said, we would need to keep a mapping from identifiers to native views in the module.

Although this solution is complex, it is used in RCTUIManager, which is an internal React Native class that manages all React Native views.

Native modules can also be used to expose existing native libraries to JS. Geolocation library is a living example of the idea.

Warning: -All native modules share the same namespace. Watch out for name collisions when creating new ones.

Layout computation flow #

When integrating native and React Native, we also need a way to consolidate two different layout systems. This section covers common layouting problems and provides a brief description of mechanisms that are intended to address them.

Layout of a native component embedded in React Native #

This case is covered in this article. Basically, as all our native react views are subclasses of UIView, most style and size attributes will work like you would expect out of the box.

Layout of a React Native component embedded in native #

React Native content with fixed size #

The simplest scenario is when we have a React Native app with a fixed size, which is known to the native side. In particular, a full-screen React Native view falls into this case. If we want a smaller root view, we can explicitly set RCTRootView's frame.

For instance, to make an RN app 200 (logical) pixels high, and the hosting view's width wide, we could do:

// SomeViewController.m +Currently, JS functions componentWillReceiveProps and componentWillUpdateProps of the top level RN component will not be called after a prop update. However, you can access the new props in componentWillMount function.

Passing properties from React Native to native #

The problem exposing properties of native components is covered in detail in this article. In short, export properties with RCT_CUSTOM_VIEW_PROPERTY macro in your custom native component, then just use them in React Native as if the component was an ordinary React Native component.

Limits of properties #

The main drawback of cross-language properties is that they do not support callbacks, which would allow us to handle bottom-up data bindings. Imagine you have a small RN view that you want to be removed from the native parent view as a result of a JS action. There is no way to do that with props, as the information would need to go bottom-up.

Although we have a flavor of cross-language callbacks (described here), these callbacks are not always the thing we need. The main problem is that they are not intended to be passed as properties. Rather, this mechanism allows us to trigger a native action from JS, and handle the result of that action in JS.

Other ways of cross-language interaction (events and native modules) #

As stated in the previous chapter, using properties comes with some limitations. Sometimes properties are not enough to drive the logic of our app and we need a solution that gives more flexibility. This chapter covers other communication techniques available in React Native. They can be used for internal communication (between JS and native layers in RN) as well as for external communication (between RN and the 'pure native' part of your app).

React Native enables you to perform cross-language function calls. You can execute custom native code from JS and vice versa. Unfortunately, depending on the side we are working on, we achieve the same goal in different ways. For native - we use events mechanism to schedule an execution of a handler function in JS, while for React Native we directly call methods exported by native modules.

Calling React Native functions from native (events) #

Events are described in detail in this article. Note that using events gives us no guarantees about execution time, as the event is handled on a separate thread.

Events are powerful, because they allow us to change React Native components without needing a reference to them. However, there are some pitfalls that you can fall into while using them:

  • As events can be sent from anywhere, they can introduce spaghetti-style dependencies into your project.
  • Events share namespace, which means that you may encounter some name collisions. Collisions will not be detected statically, what makes them hard to debug.
  • If you use several instances of the same React Native component and you want to distinguish them from the perspective of your event, you'll likely need to introduce some kind of identifiers and pass them along with events (you can use the native view's reactTag as an identifier).

The common pattern we use when embedding native in React Native is to make the native component's RCTViewManager a delegate for the views, sending events back to JavaScript via the bridge. This keeps related event calls in one place.

Calling native functions from React Native (native modules) #

Native modules are Objective-C classes that are available in JS. Typically one instance of each module is created per JS bridge. They can export arbitrary functions and constants to React Native. They have been covered in detail in this article.

The fact that native modules are singletons limits the mechanism in context of embedding. Let's say we have a React Native component embedded in a native view and we want to update the native, parent view. Using the native module mechanism, we would export a function that not only takes expected arguments, but also an identifier of the parent native view. The identifier would be used to retrieve a reference to the parent view to update. That said, we would need to keep a mapping from identifiers to native views in the module.

Although this solution is complex, it is used in RCTUIManager, which is an internal React Native class that manages all React Native views.

Native modules can also be used to expose existing native libraries to JS. Geolocation library is a living example of the idea.

Warning: +All native modules share the same namespace. Watch out for name collisions when creating new ones.

Layout computation flow #

When integrating native and React Native, we also need a way to consolidate two different layout systems. This section covers common layouting problems and provides a brief description of mechanisms that are intended to address them.

Layout of a native component embedded in React Native #

This case is covered in this article. Basically, as all our native react views are subclasses of UIView, most style and size attributes will work like you would expect out of the box.

Layout of a React Native component embedded in native #

React Native content with fixed size #

The simplest scenario is when we have a React Native app with a fixed size, which is known to the native side. In particular, a full-screen React Native view falls into this case. If we want a smaller root view, we can explicitly set RCTRootView's frame.

For instance, to make an RN app 200 (logical) pixels high, and the hosting view's width wide, we could do:

// SomeViewController.m - (void)viewDidLoad { @@ -43,7 +42,7 @@ All native modules share the same namespace. Watch out for name collisions when initialProperties:props]; rootView.frame = CGMakeRect(0, 0, self.view.width, 200); [self.view addSubview:rootView]; -}

When we have a fixed size root view, we need to respect its bounds on the JS side. In other words, we need to ensure that the React Native content can be contained within the fixed-size root view. The easiest way to ensure this is to use flexbox layout. If you use absolute positioning, and React components are visible outside the root view's bounds, you'll get overlap with native views, causing some features to behave unexpectedly. For instance, 'TouchableHighlight' will not highlight your touches outside the root view's bounds.

It's totally fine to update root view's size dynamically by re-setting its frame property. React Native will take care of the content's layout.

React Native content with flexible size #

In some cases we'd like to render content of initially unknown size. Let's say the size will be defined dynamically in JS. We have two solutions to this problem.

  1. You can wrap your React Native view in ScrollView component. This guarantees that your content will always be available and it won't overlap with native views.
  2. React Native allows you to determine, in JS, the size of the RN app and provide it to the owner of the hosting RCTRootView. The owner is then responsible for re-laying out the subviews and keeping the UI consistent. We achieve this with RCTRootView's flexibility modes.

RCTRootView supports 4 different size flexibility modes:

// RCTRootView.h +}

When we have a fixed size root view, we need to respect its bounds on the JS side. In other words, we need to ensure that the React Native content can be contained within the fixed-size root view. The easiest way to ensure this is to use flexbox layout. If you use absolute positioning, and React components are visible outside the root view's bounds, you'll get overlap with native views, causing some features to behave unexpectedly. For instance, 'TouchableHighlight' will not highlight your touches outside the root view's bounds.

It's totally fine to update root view's size dynamically by re-setting its frame property. React Native will take care of the content's layout.

React Native content with flexible size #

In some cases we'd like to render content of initially unknown size. Let's say the size will be defined dynamically in JS. We have two solutions to this problem.

  1. You can wrap your React Native view in ScrollView component. This guarantees that your content will always be available and it won't overlap with native views.
  2. React Native allows you to determine, in JS, the size of the RN app and provide it to the owner of the hosting RCTRootView. The owner is then responsible for re-laying out the subviews and keeping the UI consistent. We achieve this with RCTRootView's flexibility modes.

RCTRootView supports 4 different size flexibility modes:

// RCTRootView.h typedef NS_ENUM(NSInteger, RCTRootViewSizeFlexibility) { RCTRootViewSizeFlexibilityNone = 0, @@ -73,7 +72,7 @@ Making a dimension flexible in both JS and native leads to undefined behavior. F newFrame.size = rootView.intrinsicSize; rootView.frame = newFrame; -}

In the example we have a FlexibleSizeExampleView view that holds a root view. We create the root view, initialize it and set the delegate. The delegate will handle size updates. Then, we set the root view's size flexibility to RCTRootViewSizeFlexibilityHeight, which means that rootViewDidChangeIntrinsicSize: method will be called every time the React Native content changes its height. Finally, we set the root view's width and position. Note that we set there height as well, but it has no effect as we made the height RN-dependent.

You can checkout full source code of the example here.

It's fine to change root view's size flexibility mode dynamically. Changing flexibility mode of a root view will schedule a layout recalculation and the delegate rootViewDidChangeIntrinsicSize: method will be called once the content size is known.

Note: React Native layout calculation is performed on a special thread, while native UI view updates are done on the main thread. This may cause temporary UI inconsistencies between native and React Native. This is a known problem and our team is working on synchronizing UI updates coming from different sources.

Note: React Native does not perform any layout calculations until the root view becomes a subview of some other views. If you want to hide React Native view until its dimensions are known, add the root view as a subview and make it initially hidden (use UIView's hidden property). Then change its visibility in the delegate method.

© 2015 Facebook Inc.

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. + date: new Date(2020, 4, 25) + }); + if (action !== DatePickerAndroid.dismissedAction) { + // Selected year, month (0-11), day + } +} catch ({code, message}) { + console.warn('Cannot open date picker', message); +}

Methods #

static open(options: Object) #

Opens the standard Android date picker dialog.

The available keys for the options object are: + date (Date object or timestamp in milliseconds) - date to show by default + minDate (Date or timestamp in milliseconds) - minimum date that can be selected + * maxDate (Date object or timestamp in milliseconds) - minimum date that can be selected

Returns a Promise which will be invoked an object containing action, year, month (0-11), +day if the user picked a date. If the user dismissed the dialog, the Promise will +still be resolved with action being DatePickerAndroid.dismissedAction and all the other keys +being undefined. Always check whether the action before reading the values.

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

static dateSetAction() #

A date has been selected.

static dismissedAction() #

The dialog has been dismissed.

Examples #

Edit on GitHub
'use strict'; + +var React = require('react-native'); +var { + DatePickerAndroid, + StyleSheet, + Text, + TouchableWithoutFeedback, +} = React; + +var UIExplorerBlock = require('./UIExplorerBlock'); +var UIExplorerPage = require('./UIExplorerPage'); + +var DatePickerAndroidExample = React.createClass({ + + statics: { + title: 'DatePickerAndroid', + description: 'Standard Android date picker dialog', + }, + + getInitialState() { + return { + presetDate: new Date(2020, 4, 5), + allDate: new Date(2020, 4, 5), + simpleText: 'pick a date', + minText: 'pick a date, no earlier than today', + maxText: 'pick a date, no later than today', + presetText: 'pick a date, preset to 2020/5/5', + allText: 'pick a date between 2020/5/1 and 2020/5/10', + }; + }, + + async showPicker(stateKey, options) { + try { + var newState = {}; + const {action, year, month, day} = await DatePickerAndroid.open(options); + if (action === DatePickerAndroid.dismissedAction) { + newState[stateKey + 'Text'] = 'dismissed'; + } else { + var date = new Date(year, month, day); + newState[stateKey + 'Text'] = date.toLocaleDateString(); + newState[stateKey + 'Date'] = date; + } + this.setState(newState); + } catch ({code, message}) { + console.warn(`Error in example '${stateKey}': `, message); + } + }, + + render() { + return ( + <UIExplorerPage title="DatePickerAndroid"> + <UIExplorerBlock title="Simple date picker"> + <TouchableWithoutFeedback + onPress={this.showPicker.bind(this, 'simple', {date: this.state.simpleDate})}> + <Text style={styles.text}>{this.state.simpleText}</Text> + </TouchableWithoutFeedback> + </UIExplorerBlock> + <UIExplorerBlock title="Date picker with pre-set date"> + <TouchableWithoutFeedback + onPress={this.showPicker.bind(this, 'preset', {date: this.state.presetDate})}> + <Text style={styles.text}>{this.state.presetText}</Text> + </TouchableWithoutFeedback> + </UIExplorerBlock> + <UIExplorerBlock title="Date picker with minDate"> + <TouchableWithoutFeedback + onPress={this.showPicker.bind(this, 'min', { + date: this.state.minDate, + minDate: new Date(), + })}> + <Text style={styles.text}>{this.state.minText}</Text> + </TouchableWithoutFeedback> + </UIExplorerBlock> + <UIExplorerBlock title="Date picker with maxDate"> + <TouchableWithoutFeedback + onPress={this.showPicker.bind(this, 'max', { + date: this.state.maxDate, + maxDate: new Date(), + })}> + <Text style={styles.text}>{this.state.maxText}</Text> + </TouchableWithoutFeedback> + </UIExplorerBlock> + <UIExplorerBlock title="Date picker with all options"> + <TouchableWithoutFeedback + onPress={this.showPicker.bind(this, 'all', { + date: this.state.allDate, + minDate: new Date(2020, 4, 1), + maxDate: new Date(2020, 4, 10), + })}> + <Text style={styles.text}>{this.state.allText}</Text> + </TouchableWithoutFeedback> + </UIExplorerBlock> + </UIExplorerPage> + ); + }, +}); + +var styles = StyleSheet.create({ + text: { + color: 'black', + }, +}); + +module.exports = DatePickerAndroidExample;
© 2016 Facebook Inc.
\ No newline at end of file diff --git a/docs/datepickerios.html b/docs/datepickerios.html index 7a9b4f81722..02ffdaa1743 100644 --- a/docs/datepickerios.html +++ b/docs/datepickerios.html @@ -1,12 +1,12 @@ -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 -source of truth.

Props #

date Date #

The currently selected date.

maximumDate Date #

Maximum date.

Restricts the range of possible date/time values.

minimumDate Date #

Minimum date.

Restricts the range of possible date/time values.

minuteInterval enum(1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30) #

The interval at which minutes can be selected.

mode enum('date', 'time', 'datetime') #

The date picker mode.

onDateChange function #

Date change handler.

This is called when the user changes the date or time in the UI. +source of truth.

Props #

date Date #

The currently selected date.

maximumDate Date #

Maximum date.

Restricts the range of possible date/time values.

minimumDate Date #

Minimum date.

Restricts the range of possible date/time values.

minuteInterval enum(1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30) #

The interval at which minutes can be selected.

mode enum('date', 'time', 'datetime') #

The date picker mode.

onDateChange function #

Date change handler.

This is called when the user changes the date or time in the UI. The first and only argument is a Date object representing the new -date and time.

timeZoneOffsetInMinutes number #

Timezone offset in minutes.

By default, the date picker will use the device's timezone. With this +date and time.

timeZoneOffsetInMinutes number #

Timezone offset in minutes.

By default, the date picker will use the device's timezone. With this parameter, it is possible to force a certain timezone offset. For -instance, to show times in Pacific Standard Time, pass -7 * 60.

Examples #

Edit on GitHub
'use strict'; +instance, to show times in Pacific Standard Time, pass -7 * 60.

Examples #

Edit on GitHub
'use strict'; var React = require('react-native'); var { @@ -158,7 +158,7 @@ exports.examples : '500', fontSize: 14, }, -});
© 2015 Facebook Inc.

Debugging #

Edit on GitHub

Debugging React Native Apps #

To access the in-app developer menu:

  1. On iOS shake the device or press control + ⌘ + z in the simulator.
  2. On Android shake the device or press hardware menu button (available on older devices and in most of the emulators, e.g. in genymotion you can press ⌘ + m to simulate hardware menu button click). You can also install Frappé, a tool for OS X, which allows you to emulate shaking of devices remotely. You can use ⌘ + Shift + R as a shortcut to trigger a shake from Frappé.

Hint

To disable the developer menu for production builds:

  1. For iOS open your project in Xcode and select ProductSchemeEdit Scheme... (or press ⌘ + <). Next, select Run from the menu on the left and change the Build Configuration to Release.
  2. For Android, by default, developer menu will be disabled in release builds done by gradle (e.g with gradle assembleRelease task). Although this behavior can be customized by passing proper value to ReactInstanceManager#setUseDeveloperSupport.

Reload #

Selecting Reload (or pressing ⌘ + r in the iOS simulator) will reload the JavaScript that powers your application. If you have added new resources (such as an image to Images.xcassets on iOS or to res/drawable folder on Android) or modified any native code (Objective-C/Swift code on iOS or Java/C++ code on Android), you will need to re-build the app for the changes to take effect.

Chrome Developer Tools #

To debug the JavaScript code in Chrome, select Debug in Chrome from the developer menu. This will open a new tab at http://localhost:8081/debugger-ui.

In Chrome, press ⌘ + option + i or select ViewDeveloperDeveloper Tools to toggle the developer tools console. Enable Pause On Caught Exceptions for a better debugging experience.

To debug on a real device:

  1. On iOS - open the file RCTWebSocketExecutor.m and change localhost to the IP address of your computer. Shake the device to open the development menu with the option to start debugging.
  2. On Android, if you're running Android 5.0+ device connected via USB you can use adb command line tool to setup port forwarding from the device to your computer. For that run: adb reverse tcp:8081 tcp:8081 (see this link for help on adb command). Alternatively, you can open dev menu on the device and select Dev Settings, then update Debug server host for device setting to the IP address of your computer.

React Developer Tools (optional) #

Install the React Developer Tools extension for Google Chrome. This will allow you to navigate the component hierarchy via the React in the developer tools (see facebook/react-devtools for more information).

Live Reload #

This option allows for your JS changes to trigger automatic reload on the connected device/emulator. To enable this option:

  1. On iOS, select Enable Live Reload via the developer menu to have the application automatically reload when changes are made to the JavaScript.
  2. On Android, launch dev menu, go to Dev Settings and select Auto reload on JS change option

FPS (Frames per Second) Monitor #

On 0.5.0-rc and higher versions, you can enable a FPS graph overlay in the developers menu in order to help you debug performance problems.

© 2015 Facebook Inc.

Debugging #

Edit on GitHub

Debugging React Native Apps #

To access the in-app developer menu:

  1. On iOS shake the device or press control + ⌘ + z in the simulator.
  2. On Android shake the device or press hardware menu button (available on older devices and in most of the emulators, e.g. in genymotion you can press ⌘ + m to simulate hardware menu button click). You can also install Frappé, a tool for OS X, which allows you to emulate shaking of devices remotely. You can use ⌘ + Shift + R as a shortcut to trigger a shake from Frappé.

Hint

To disable the developer menu for production builds:

  1. For iOS open your project in Xcode and select ProductSchemeEdit Scheme... (or press ⌘ + <). Next, select Run from the menu on the left and change the Build Configuration to Release.
  2. For Android, by default, developer menu will be disabled in release builds done by gradle (e.g with gradle assembleRelease task). Although this behavior can be customized by passing proper value to ReactInstanceManager#setUseDeveloperSupport.

Android logging #

Run adb logcat *:S ReactNative:V ReactNativeJS:V in a terminal to see your Android app's logs.

Reload #

Selecting Reload (or pressing ⌘ + r in the iOS simulator) will reload the JavaScript that powers your application. If you have added new resources (such as an image to Images.xcassets on iOS or to res/drawable folder on Android) or modified any native code (Objective-C/Swift code on iOS or Java/C++ code on Android), you will need to re-build the app for the changes to take effect.

YellowBox/RedBox #

Using console.warn will display an on-screen log on a yellow background. Click on this warning to show more information about it full screen and/or dismiss the warning.

You can use console.error to display a full screen error on a red background.

These boxes only appear when you're running your app in dev mode.

Chrome Developer Tools #

To debug the JavaScript code in Chrome, select Debug in Chrome from the developer menu. This will open a new tab at http://localhost:8081/debugger-ui.

In Chrome, press ⌘ + option + i or select ViewDeveloperDeveloper Tools to toggle the developer tools console. Enable Pause On Caught Exceptions for a better debugging experience.

To debug on a real device:

  1. On iOS - open the file RCTWebSocketExecutor.m and change localhost to the IP address of your computer. Shake the device to open the development menu with the option to start debugging.
  2. On Android, if you're running Android 5.0+ device connected via USB you can use adb command line tool to setup port forwarding from the device to your computer. For that run: adb reverse tcp:8081 tcp:8081 (see this link for help on adb command). Alternatively, you can open dev menu on the device and select Dev Settings, then update Debug server host for device setting to the IP address of your computer.

React Developer Tools (optional) #

Install the React Developer Tools extension for Google Chrome. This will allow you to navigate the component hierarchy via the React in the developer tools (see facebook/react-devtools for more information).

Live Reload #

This option allows for your JS changes to trigger automatic reload on the connected device/emulator. To enable this option:

  1. On iOS, select Enable Live Reload via the developer menu to have the application automatically reload when changes are made to the JavaScript.
  2. On Android, launch dev menu, go to Dev Settings and select Auto reload on JS change option

FPS (Frames per Second) Monitor #

On 0.5.0-rc and higher versions, you can enable a FPS graph overlay in the developers menu in order to help you debug performance problems.

© 2016 Facebook Inc.

Dimensions #

Edit on GitHub

Methods #

static set(dims: {[key:string]: any}) #

This should only be called from native code.

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

static get(dim: string) #

Initial dimensions are set before runApplication is called so they should +Dimensions – React Native | A framework for building native apps using React

Dimensions #

Edit on GitHub

Methods #

static set(dims: {[key:string]: any}) #

This should only be called from native code.

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

static get(dim: string) #

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 these constants should try to call this function on every render, rather than caching the value (for example, using inline styles rather than setting a value in a StyleSheet).

Example: var {height, width} = Dimensions.get('window');

@param {string} dim Name of dimension as defined when calling set. -@returns {Object?} Value for the dimension.

© 2015 Facebook Inc.

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 @@ -10,7 +10,7 @@ hierarchy and reconciling many views. setNativeProps is imperative and stores state in the native layer (DOM, UIView, etc.) and not within your React components, which makes your code more difficult to reason about. Before you use it, try to solve your problem with setState -and shouldComponentUpdate.

setNativeProps with TouchableOpacity #

TouchableOpacity +and shouldComponentUpdate.

setNativeProps with TouchableOpacity #

TouchableOpacity uses setNativeProps internally to update the opacity of its child component:

setOpacityTo: function(value) { // Redacted: animation related code @@ -48,7 +48,7 @@ optimizing your components can improve your animations' fidelity.

If you will notice that it is a wrapper around RCTUIManager.updateView - this is the exact same function call that results from re-rendering - see receiveComponent in -ReactNativeBaseComponent.js.

Composite components and setNativeProps #

Composite components are not backed by a native view, so you cannot call +ReactNativeBaseComponent.js.

Composite components and setNativeProps #

Composite components are not backed by a native view, so you cannot call setNativeProps on them. Consider this example:

var MyButton = React.createClass({ render() { return ( @@ -75,7 +75,7 @@ define a component with React.createClass you would not expect to b able to set a style prop on it and have that work - you would need to pass the style prop down to a child, unless you are wrapping a native component. Similarly, we are going to forward setNativeProps to a -native-backed child component.

Forward setNativeProps to a child #

All we need to do is provide a setNativeProps method on our component +native-backed child component.

Forward setNativeProps to a child #

All we need to do is provide a setNativeProps method on our component that calls setNativeProps on the appropriate child with the given arguments.

var MyButton = React.createClass({ setNativeProps(nativeProps) { @@ -98,7 +98,7 @@ child perform touch handling. To do this, it passes on setNativeProps to clear TextInput value #

Another very common use case of setNativeProps is to clear the value +requires that we implement setNativeProps.

setNativeProps to clear TextInput value #

Another very common use case of setNativeProps is to clear the value of a TextInput. The controlled prop of TextInput can sometimes drop characters when the bufferDelay is low and the user types very quickly. Some developers prefer to skip this prop entirely and instead @@ -120,17 +120,17 @@ input when you tap a button:

/View> ); } -});

Run this example

Avoiding conflicts with the render function #

If you update a property that is also managed by the render function, +});

Run this example

Avoiding conflicts with the render function #

If you update a property that is also managed by the render function, you might end up with some unpredictable and confusing bugs because anytime the component re-renders and that property changes, whatever value was previously set from setNativeProps will be completely ignored and overridden. See this example for a demonstration of what can happen if these two collide - notice -the jerky animation each 250ms when setState triggers a re-render.

setNativeProps & shouldComponentUpdate #

By intelligently applying +the jerky animation each 250ms when setState triggers a re-render.

setNativeProps & shouldComponentUpdate #

By intelligently applying shouldComponentUpdate you can avoid the unnecessary overhead involved in reconciling unchanged component subtrees, to the point where it may be performant enough to -use setState instead of setNativeProps.

© 2015 Facebook Inc.

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 @@ -20,14 +20,14 @@ be set by the drawerWidth prop.

Example:

/View> </DrawerLayoutAndroid> ); -},

Props #

drawerPosition enum(DrawerConsts.DrawerPosition.Left, DrawerConsts.DrawerPosition.Right) #

Specifies the side of the screen from which the drawer will slide in.

drawerWidth number #

Specifies the width of the drawer, more precisely the width of the view that be pulled in -from the edge of the window.

keyboardDismissMode enum('none', 'on-drag') #

Determines whether the keyboard gets dismissed in response to a drag. +},

Props #

drawerPosition enum(DrawerConsts.DrawerPosition.Left, DrawerConsts.DrawerPosition.Right) #

Specifies the side of the screen from which the drawer will slide in.

drawerWidth number #

Specifies the width of the drawer, more precisely the width of the view that be pulled in +from the edge of the window.

keyboardDismissMode enum('none', 'on-drag') #

Determines whether the keyboard gets dismissed in response to a drag. - 'none' (the default), drags do not dismiss the keyboard. - - 'on-drag', the keyboard is dismissed when a drag begins.

onDrawerClose function #

Function called whenever the navigation view has been closed.

onDrawerOpen function #

Function called whenever the navigation view has been opened.

onDrawerSlide function #

Function called whenever there is an interaction with the navigation view.

onDrawerStateChanged function #

Function called when the drawer state has changed. The drawer can be in 3 states: + - 'on-drag', the keyboard is dismissed when a drag begins.

onDrawerClose function #

Function called whenever the navigation view has been closed.

onDrawerOpen function #

Function called whenever the navigation view has been opened.

onDrawerSlide function #

Function called whenever there is an interaction with the navigation view.

onDrawerStateChanged function #

Function called when the drawer state has changed. The drawer can be in 3 states: - idle, meaning there is no interaction with the navigation view happening at the time - dragging, meaning there is currently an interaction with the navigation view - settling, meaning that there was an interaction with the navigation view, and the -navigation view is now finishing it's closing or opening animation

renderNavigationView function #

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

© 2015 Facebook Inc.

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:0.17.+'

You can find the latest version of the react-native library on Maven Central. 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 { +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:0.17.+'

You can find the latest version of the react-native library on Maven Central. 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; @@ -55,15 +55,14 @@ public boolean onKeyUpreturn 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 project's root folder, run:

$ npm init +}

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

Add JS to your app #

In your project'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_modules/react-native/packager/packager.sh"

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

'use strict'; -var React = require('react-native'); -var { +import React, { Text, View -} = React; +} from 'react-native'; class MyAwesomeApp extends React.Component { render() { @@ -86,7 +85,7 @@ class MyAwesomeApp extends }, }); -React.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.

© 2015 Facebook Inc.

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 #

  • CocoaPodsgem 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 +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 #

  • CocoaPodsgem 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', @@ -7,14 +7,13 @@ pod 'React''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 +]

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'; -var React = require('react-native'); -var { +import React, { Text, View -} = React; +} from 'react-native'; var styles = React.StyleSheet.create({ container: { @@ -33,7 +32,7 @@ class SimpleApp extends } } -React.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 +React.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 @@ -41,7 +40,7 @@ React.AppRegistryViewController () @property (weak, nonatomic) IBOutlet ReactView *reactView; -@end

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"]; +@end

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"]; @@ -53,7 +52,7 @@ React.AppRegistry: @"SimpleApp" initialProperties:nil launchOptions:nil];

Then add it as a subview of the ReactView.

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

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 ReactComponents 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> +rootView.frame = self.bounds;

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 ReactComponents 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> @@ -63,7 +62,7 @@ rootView.frame 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 (make sure that DEBUG=1 is set under Build Settings -> Preprocessor Macros). 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.

© 2015 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', 'column') #

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 #

padding number #

paddingBottom number #

paddingHorizontal number #

paddingLeft number #

paddingRight number #

paddingTop number #

paddingVertical number #

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

right number #

top number #

width number #

© 2015 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', 'column') #

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 #

padding number #

paddingBottom number #

paddingHorizontal number #

paddingLeft number #

paddingRight number #

paddingTop number #

paddingVertical number #

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

right number #

top number #

width number #

© 2016 Facebook Inc.

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 +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 -app's AndroidManifest.xml:

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

Methods #

static getCurrentPosition(geo_success: Function, geo_error?: Function, geo_options?: GeoOptions) #

Invokes the success callback once with the latest location info. Supported -options: timeout (ms), maximumAge (ms), enableHighAccuracy (bool)

static watchPosition(success: Function, error?: Function, options?: GeoOptions) #

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

static clearWatch(watchID: number) #

static stopObserving() #

Examples #

Edit on GitHub
/* eslint no-console: 0 */ +when you create a project with react-native init.

Android #

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

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

Methods #

static getCurrentPosition(geo_success: Function, geo_error?: Function, geo_options?: GeoOptions) #

Invokes the success callback once with the latest location info. Supported +options: timeout (ms), maximumAge (ms), enableHighAccuracy (bool)

static watchPosition(success: Function, error?: Function, options?: GeoOptions) #

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

static clearWatch(watchID: number) #

static stopObserving() #

Examples #

Edit on GitHub
/* eslint no-console: 0 */ 'use strict'; @@ -77,7 +77,7 @@ exports.examples : { fontWeight: '500', }, -});
© 2015 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.

© 2015 Facebook Inc.

Gesture Responder System #

Edit on GitHub

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

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

Best Practices #

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

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

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

TouchableHighlight and Touchable* #

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

Responder Lifecycle #

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

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

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

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

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

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

evt is a synthetic touch event with the following form:

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

Capture ShouldSet Handlers #

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

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

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

PanResponder #

For higher-level gesture interpretation, check out PanResponder.

© 2016 Facebook Inc.

Getting Started on Linux #

Edit on GitHub

This guide is essentially a beginner-friendly version of the Getting Started page for React Native on Linux.

Prerequisites #

For the purposes of this guide, we assume that you're working on Ubuntu Linux 14.04 LTS.

Before following this guide, you should have installed the Android SDK and run a successful Java-based "Hello World" app for Android.

See Android Setup for details.

Installing NodeJS #

The first thing you need to do is to install NodeJS, a popular Javascript implementation.

Fire up the Terminal and paste the following commands to install NodeJS from the NodeSource repository:

sudo apt-get install -y build-essential +curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash - +sudo apt-get install -y nodejs +sudo ln -s /usr/bin/nodejs /usr/bin/node

NOTE: The above instructions are for Ubuntu. If you're on a different distro, please follow the instructions on the NodeJS website.

Installing Watchman #

watchman is a tool by Facebook for watching changes in the filesystem. You need to install it for better performance and avoid a node file-watching bug.

Paste the following into your terminal to compile watchman from source and install it:

git clone https://github.com/facebook/watchman.git +cd watchman +git checkout v4.1.0 # the latest stable release +./autogen.sh +./configure +make +sudo make install

Installing Flow #

Flow is a static type checker for JavaScript. To install it, paste the following in the terminal:

sudo npm install -g flow-bin

Setting up an Android Device #

Let's set up an Android device to run our starter project.

First thing is to plug in your device and check the manufacturer code by using lsusb, which should output something like this:

$ lsusb +Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub +Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub +Bus 001 Device 003: ID 22b8:2e76 Motorola PCS +Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub +Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub +Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub +Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

These lines represent the USB devices currently connected to your machine.

You want the line that represents your phone. If you're in doubt, try unplugging your phone and running the command again:

$ lsusb +Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub +Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub +Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub +Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub +Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub +Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

You'll see that after removing the phone, the line which has the phone model ("Motorola PCS" in this case) disappeared from the list. This is the line that we care about.

Bus 001 Device 003: ID 22b8:2e76 Motorola PCS

From the above line, you want to grab the first four digits from the device ID:

22b8:2e76

In this case, it's 22b8. That's the identifier for Motorola.

You'll need to input this into your udev rules in order to get up and running:

echo SUBSYSTEM=="usb", ATTR{idVendor}=="22b8", MODE="0666", GROUP="plugdev" | sudo tee /etc/udev/rules.d/51-android-usb.rules

Make sure that you replace 22b8 with the identifier you get in the above command.

Now check that your device is properly connecting to ADB, the Android Debug Bridge, by using adb devices.

List of devices attached +TA9300GLMK device

For more information, please see the docs for running an Android app on your device.

Next Steps #

Your Android device and your tools are all ready to go. You can now follow the instructions in the Quick Start guide to install React Native and start your first project.

© 2016 Facebook Inc.
\ No newline at end of file diff --git a/docs/getting-started.html b/docs/getting-started.html index 45139a904fc..9f15661b363 100644 --- a/docs/getting-started.html +++ b/docs/getting-started.html @@ -1,5 +1,4 @@ -Getting Started – React Native | A framework for building native apps using React

Getting Started #

Edit on GitHub

Requirements #

  1. OS X - This guide assumes OS X which is needed for iOS development.
  2. Homebrew is the recommended way to install Watchman and Flow.
  3. Install Node.js 4.0 or newer.
    • 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.
    • New to npm?
  4. brew install watchman. We recommend installing watchman, otherwise you might hit a node file watching bug.
  5. brew install flow, if you want to use flow.

We recommend periodically running brew update && brew upgrade to keep your programs up-to-date.

iOS Setup #

Xcode 7.0 or higher is required. It can be installed from the App Store.

Android Setup #

To write React Native apps for Android, you will need to install the Android SDK (and an Android emulator if you want to work on your app without having to use a physical device). See Android setup guide for instructions on how to set up your Android environment.

NOTE: There is experimental Windows and Linux support for Android development.

Quick start #

$ npm install -g react-native-cli -$ react-native init AwesomeProject

To run the iOS app:

  • $ cd AwesomeProject
  • Open ios/AwesomeProject.xcodeproj and hit run in Xcode.
  • Open index.ios.js in your text editor of choice and edit some lines.
  • Hit ⌘-R in your iOS simulator to reload the app and see your change!

Note: If you are using an iOS device, see the Running on iOS Device page.

To run the Android app:

  • $ cd AwesomeProject
  • $ react-native run-android
  • Open index.android.js in your text editor of choice and edit some lines.
  • Press the menu button (F2 by default, or ⌘-M in Genymotion) and select Reload JS to see your change!
  • Run adb logcat *:S ReactNative:V ReactNativeJS:V in a terminal to see your app's logs

Note: If you are using an Android device, see the Running on Android Device page.

Congratulations! You've successfully run and modified your first React Native app.

If you run into any issues getting started, see the troubleshooting page.

Adding Android to an existing React Native project #

If you already have a (iOS-only) React Native project and want to add Android support, you need to execute the following commands in your existing project directory:

  1. Update the react-native dependency in your package.json file to the latest version
  2. $ npm install
  3. $ react-native android
© 2015 Facebook Inc.

Getting Started #

Edit on GitHub

Requirements #

  1. OS X - This guide assumes OS X which is needed for iOS development.
  2. Homebrew is the recommended way to install Watchman and Flow.
  3. Install Node.js 4.0 or newer.
    • 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.
    • New to npm?
  4. brew install watchman. We recommend installing watchman, otherwise you might hit a node file watching bug.
  5. brew install flow, if you want to use flow.

We recommend periodically running brew update && brew upgrade to keep your programs up-to-date.

iOS Setup #

Xcode 7.0 or higher is required. It can be installed from the App Store.

Android Setup #

To write React Native apps for Android, you will need to install the Android SDK (and an Android emulator if you want to work on your app without having to use a physical device). See Android setup guide for instructions on how to set up your Android environment.

NOTE: There is experimental Windows and Linux support for Android development.

Quick start #

Install the React Native command line tools:

$ npm install -g react-native-cli

NOTE: If you see the error, EACCES: permission denied, please run the command: sudo npm install -g react-native-cli.

Create a React Native project:

$ react-native init AwesomeProject

To run the iOS app:

  • $ cd AwesomeProject
  • Open ios/AwesomeProject.xcodeproj and hit run in Xcode.
  • Open index.ios.js in your text editor of choice and edit some lines.
  • Hit ⌘-R in your iOS simulator to reload the app and see your change!

Note: If you are using an iOS device, see the Running on iOS Device page.

To run the Android app:

  • $ cd AwesomeProject
  • $ react-native run-android
  • Open index.android.js in your text editor of choice and edit some lines.
  • Press the menu button (F2 by default, or ⌘-M in Genymotion) and select Reload JS to see your change!
  • Run adb logcat *:S ReactNative:V ReactNativeJS:V in a terminal to see your app's logs

Note: If you are using an Android device, see the Running on Android Device page.

Congratulations! You've successfully run and modified your first React Native app.

If you run into any issues getting started, see the troubleshooting page.

Adding Android to an existing React Native project #

If you already have a (iOS-only) React Native project and want to add Android support, you need to execute the following commands in your existing project directory:

  1. Update the react-native dependency in your package.json file to the latest version
  2. $ npm install
  3. $ react-native android
© 2016 Facebook Inc.

Image #

Edit on GitHub

A React component for displaying different types of images, +Image – React Native | A framework for building native apps using React

Image #

Edit on GitHub

A React component for displaying different types of images, including network images, static resources, temporary local images, and images from local disk, such as the camera roll.

Example usage:

renderImages: function() { return ( @@ -13,16 +13,16 @@ images from local disk, such as the camera roll.

Example usage:

/> </View> ); -},

Props #

onLayout function #

Invoked on mount and layout changes with -{nativeEvent: {layout: {x, y, width, height}}}.

onLoad function #

Invoked when load completes successfully

onLoadEnd function #

Invoked when load either succeeds or fails

onLoadStart function #

Invoked on load start

resizeMode enum('cover', 'contain', 'stretch') #

Determines how to resize the image when the frame doesn't match the raw +},

Props #

onLayout function #

Invoked on mount and layout changes with +{nativeEvent: {layout: {x, y, width, height}}}.

onLoad function #

Invoked when load completes successfully

onLoadEnd function #

Invoked when load either succeeds or fails

onLoadStart function #

Invoked on load start

resizeMode enum('cover', 'contain', 'stretch') #

Determines how to resize the image when the frame doesn't match the raw image dimensions.

'cover': Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding).

'contain': Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or less than the corresponding dimension of the view (minus padding).

'stretch': Scale width and height independently, This may change the -aspect ratio of the src.

source {uri: string}, number #

uri is a string representing the resource identifier for the image, which +aspect ratio of the src.

source {uri: string}, number #

uri is a string representing the resource identifier for the image, which could be an http address, a local file path, or the name of a static image -resource (which should be wrapped in the require('./path/to/image.png') function).

style style #

backfaceVisibility enum('visible', 'hidden')
backgroundColor color
borderColor color
borderRadius number
borderWidth number
opacity number
overflow enum('visible', 'hidden')
resizeMode Object.keys(ImageResizeMode)
androidoverlayColor string

When the image has rounded corners, specifying an overlayColor will +resource (which should be wrapped in the require('./path/to/image.png') function).

style style #

backfaceVisibility enum('visible', 'hidden')
backgroundColor color
borderColor color
borderRadius number
borderWidth number
opacity number
overflow enum('visible', 'hidden')
resizeMode Object.keys(ImageResizeMode)
androidoverlayColor string

When the image has rounded corners, specifying an overlayColor will cause the remaining space in the corners to be filled with a solid color. This is useful in cases which are not supported by the Android implementation of rounded corners: @@ -30,14 +30,14 @@ implementation of rounded corners: - Animated GIFs

A typical way to use this prop is with images displayed on a solid background and setting the overlayColor to the same color as the background.

For details of how this works under the hood, see -http://frescolib.org/docs/rounded-corners-and-circles.html

iostintColor color

iOS-Specific style to "tint" an image. -Changes the color of all the non-transparent pixels to the tintColor.

testID string #

A unique identifier for this element to be used in UI Automation -testing scripts.

iosaccessibilityLabel string #

The text that's read by the screen reader when the user interacts with -the image.

iosaccessible bool #

When true, indicates the image is an accessibility element.

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

When the image is resized, the corners of the size specified +http://frescolib.org/docs/rounded-corners-and-circles.html

iostintColor color

iOS-Specific style to "tint" an image. +Changes the color of all the non-transparent pixels to the tintColor.

testID string #

A unique identifier for this element to be used in UI Automation +testing scripts.

iosaccessibilityLabel string #

The text that's read by the screen reader when the user interacts with +the image.

iosaccessible bool #

When true, indicates the image is an accessibility element.

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

When the image is resized, the corners of the size specified by capInsets will stay a fixed size, but the center content and borders of the image will be stretched. This is useful for creating resizable rounded buttons, shadows, and other resizable assets. More info on -Apple documentation

iosdefaultSource {uri: string}, number #

A static image to display while loading the image source.

iosonError function #

Invoked on load error with {nativeEvent: {error}}

iosonProgress function #

Invoked on download progress with {nativeEvent: {loaded, total}}

Examples #

Edit on GitHub
'use strict'; +Apple documentation

iosdefaultSource {uri: string}, number #

A static image to display while loading the image source.

iosonError function #

Invoked on load error with {nativeEvent: {error}}

iosonProgress function #

Invoked on download progress with {nativeEvent: {loaded, total}}

Examples #

Edit on GitHub
'use strict'; var React = require('react-native'); var { @@ -540,7 +540,7 @@ exports.examples : 50, resizeMode: 'contain', }, -});
© 2015 Facebook Inc.

Images #

Edit on GitHub

Static Image Resources #

As of 0.14 release, React Native provides a unified way of managing images in your iOS and Android apps. To add a static image to your app, place it somewhere in your source code tree and reference it like this:

<Image source={require('./my-icon.png')} />

The image name is resolved the same way JS modules are resolved. In the example above the packager will look for my-icon.png in the same folder as the component that requires it. Also if you have my-icon.ios.png and my-icon.android.png, the packager will pick the file depending on the platform you are running on.

You can also use @2x, @3x, etc. suffix in the file name to provide images for different screen densities. For example, if you have the following file structure:

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

Images #

Edit on GitHub

Static Image Resources #

As of 0.14 release, React Native provides a unified way of managing images in your iOS and Android apps. To add a static image to your app, place it somewhere in your source code tree and reference it like this:

<Image source={require('./my-icon.png')} />

The image name is resolved the same way JS modules are resolved. In the example above the packager will look for my-icon.png in the same folder as the component that requires it. Also if you have my-icon.ios.png and my-icon.android.png, the packager will pick the file depending on the platform you are running on.

You can also use @2x, @3x, etc. suffix in the file name to provide images for different screen densities. For example, if you have the following file structure:

. ├── button.js └── img ├── check@2x.png @@ -11,17 +11,17 @@ // GOOD var icon = this.props.active ? require('./my-icon-active.png') : require('./my-icon-inactive.png'); -<Image source={icon} />

Note that image sources required this way include size (width, height) info for the Image. If you need to scale the image dynamically (i.e. via flex), you may need to manually set { width: undefined, height: undefined } on the style attribute.

Available React Native 0.14+. If you've generated your project with 0.13 or earlier, read this. The new asset system relies on build hooks for Xcode and Gradle that are included in new projects generated with react-native init. If you generated your projects before that, you'll have to manually add them to your projects to use the new images asset system. See Upgrading for instructions on how to do this.

Images From Hybrid App's Resources #

If you are building a hybrid app (some UIs in React Native, some UIs in platform code) you can still use images that are already bundled into the app (via Xcode asset catalogs or Android drawable folder):

<Image source={{uri: 'app_icon'}} style={{width: 40, height: 40}} />

Note that this approach provides no safety checks. It's up to you to guarantee that those images are available in the application. Also you have to specify image dimensions manually.

Network Images #

Many of the images you will display in your app will not be available at compile time, or you will want to load some dynamically to keep the binary size down. Unlike with static resources, you will need to manually specify the dimensions of your image.

// GOOD +<Image source={icon} />

Note that image sources required this way include size (width, height) info for the Image. If you need to scale the image dynamically (i.e. via flex), you may need to manually set { width: undefined, height: undefined } on the style attribute.

Available React Native 0.14+. If you've generated your project with 0.13 or earlier, read this. The new asset system relies on build hooks for Xcode and Gradle that are included in new projects generated with react-native init. If you generated your projects before that, you'll have to manually add them to your projects to use the new images asset system. See Upgrading for instructions on how to do this.

Images From Hybrid App's Resources #

If you are building a hybrid app (some UIs in React Native, some UIs in platform code) you can still use images that are already bundled into the app (via Xcode asset catalogs or Android drawable folder):

<Image source={{uri: 'app_icon'}} style={{width: 40, height: 40}} />

Note that this approach provides no safety checks. It's up to you to guarantee that those images are available in the application. Also you have to specify image dimensions manually.

Network Images #

Many of the images you will display in your app will not be available at compile time, or you will want to load some dynamically to keep the binary size down. Unlike with static resources, you will need to manually specify the dimensions of your image.

// GOOD <Image source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}} style={{width: 400, height: 400}} /> // BAD -<Image source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}} />

Local Filesystem Images #

See CameraRoll for an example of -using local resources that are outside of Images.xcassets.

Best Camera Roll Image #

iOS saves multiple sizes for the same image in your Camera Roll, it is very important to pick the one that's as close as possible for performance reasons. You wouldn't want to use the full quality 3264x2448 image as source when displaying a 200x200 thumbnail. If there's an exact match, React Native will pick it, otherwise it's going to use the first one that's at least 50% bigger in order to avoid blur when resizing from a close size. All of this is done by default so you don't have to worry about writing the tedious (and error prone) code to do it yourself.

Why Not Automatically Size Everything? #

In the browser if you don't give a size to an image, the browser is going to render a 0x0 element, download the image, and then render the image based with the correct size. The big issue with this behavior is that your UI is going to jump all around as images load, this makes for a very bad user experience.

In React Native this behavior is intentionally not implemented. It is more work for the developer to know the dimensions (or aspect ratio) of the remote image in advance, but we believe that it leads to a better user experience. Static images loaded from the app bundle via the require('./my-icon.png') syntax can be automatically sized because their dimensions are available immediately at the time of mounting.

For example, the result of require('./my-icon.png') might be:

{"__packager_asset":true,"path":"/Users/react/HelloWorld/my-icon.png","uri":"my-icon.png","width":591,"height":573}

Source as an object #

In React Native, one interesting decision is that the src attribute is named source and doesn't take a string but an object with an uri attribute.

<Image source={{uri: 'something.jpg'}} />

On the infrastructure side, the reason is that it allows us to attach metadata to this object. For example if you are using require('./my-icon.png'), then we add information about its actual location and size (don't rely on this fact, it might change in the future!). This is also future proofing, for example we may want to support sprites at some point, instead of outputting {uri: ...}, we can output {uri: ..., crop: {left: 10, top: 50, width: 20, height: 40}} and transparently support spriting on all the existing call sites.

On the user side, this lets you annotate the object with useful attributes such as the dimension of the image in order to compute the size it's going to be displayed in. Feel free to use it as your data structure to store more information about your image.

Background Image via Nesting #

A common feature request from developers familiar with the web is background-image. To handle this use case, simply create a normal <Image> component and add whatever children to it you would like to layer on top of it.

return ( +<Image source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}} />

Local Filesystem Images #

See CameraRoll for an example of +using local resources that are outside of Images.xcassets.

Best Camera Roll Image #

iOS saves multiple sizes for the same image in your Camera Roll, it is very important to pick the one that's as close as possible for performance reasons. You wouldn't want to use the full quality 3264x2448 image as source when displaying a 200x200 thumbnail. If there's an exact match, React Native will pick it, otherwise it's going to use the first one that's at least 50% bigger in order to avoid blur when resizing from a close size. All of this is done by default so you don't have to worry about writing the tedious (and error prone) code to do it yourself.

Why Not Automatically Size Everything? #

In the browser if you don't give a size to an image, the browser is going to render a 0x0 element, download the image, and then render the image based with the correct size. The big issue with this behavior is that your UI is going to jump all around as images load, this makes for a very bad user experience.

In React Native this behavior is intentionally not implemented. It is more work for the developer to know the dimensions (or aspect ratio) of the remote image in advance, but we believe that it leads to a better user experience. Static images loaded from the app bundle via the require('./my-icon.png') syntax can be automatically sized because their dimensions are available immediately at the time of mounting.

For example, the result of require('./my-icon.png') might be:

{"__packager_asset":true,"path":"/Users/react/HelloWorld/my-icon.png","uri":"my-icon.png","width":591,"height":573}

Source as an object #

In React Native, one interesting decision is that the src attribute is named source and doesn't take a string but an object with an uri attribute.

<Image source={{uri: 'something.jpg'}} />

On the infrastructure side, the reason is that it allows us to attach metadata to this object. For example if you are using require('./my-icon.png'), then we add information about its actual location and size (don't rely on this fact, it might change in the future!). This is also future proofing, for example we may want to support sprites at some point, instead of outputting {uri: ...}, we can output {uri: ..., crop: {left: 10, top: 50, width: 20, height: 40}} and transparently support spriting on all the existing call sites.

On the user side, this lets you annotate the object with useful attributes such as the dimension of the image in order to compute the size it's going to be displayed in. Feel free to use it as your data structure to store more information about your image.

Background Image via Nesting #

A common feature request from developers familiar with the web is background-image. To handle this use case, simply create a normal <Image> component and add whatever children to it you would like to layer on top of it.

return ( <Image source={...}> <Text>Inside</Text> </Image> -);

Off-thread Decoding #

Image decoding can take more than a frame-worth of time. This is one of the major source of frame drops on the web because decoding is done in the main thread. In React Native, image decoding is done in a different thread. In practice, you already need to handle the case when the image is not downloaded yet, so displaying the placeholder for a few more frames while it is decoding does not require any code change.

© 2015 Facebook Inc.

IntentAndroid #

Edit on GitHub

NOTE: IntentAndroid is being deprecated. Use Linking instead.

IntentAndroid gives you a general interface to handle external links.

Basic Usage #

Handling deep links #

If your app was launched from an external url registered to your app you can +IntentAndroid – React Native | A framework for building native apps using React

IntentAndroid #

Edit on GitHub

NOTE: IntentAndroid is being deprecated. Use Linking instead.

IntentAndroid gives you a general interface to handle external links.

Basic Usage #

Handling deep links #

If your app was launched from an external url registered to your app you can access and handle it from any component you want with

componentDidMount() { var url = IntentAndroid.getInitialURL(url => { if (url) { @@ -19,18 +19,18 @@ More Info: !-- Accepts URIs that begin with "facebook://react --> <!-- <data android:scheme="facebook" android:host="react" /> --> - </intent-filter>

Opening external links #

To start the corresponding activity for a link (web URL, email, contact etc.), call

IntentAndroid.openURL(url)

If you want to check if any installed app can handle a given URL beforehand you can call

IntentAndroid.canOpenURL(url, (supported) => { + </intent-filter>

Opening external links #

To start the corresponding activity for a link (web URL, email, contact etc.), call

IntentAndroid.openURL(url)

If you want to check if any installed app can handle a given URL beforehand you can call

IntentAndroid.canOpenURL(url, (supported) => { if (!supported) { console.log('Can\'t handle url: ' + url); } else { IntentAndroid.openURL(url); } -});

Methods #

static openURL(url: string) #

Starts a corresponding external activity for the given URL.

For example, if the URL is "https://www.facebook.com", the system browser will be opened, +});

Methods #

static openURL(url: string) #

Starts a corresponding external activity for the given URL.

For example, if the URL is "https://www.facebook.com", the system browser will be opened, or the "choose application" dialog will be shown.

You can use other URLs, like a location (e.g. "geo:37.484847,-122.148386"), a contact, or any other URL that can be opened with {@code Intent.ACTION_VIEW}.

NOTE: This method will fail if the system doesn't know how to open the specified URL. -If you're passing in a non-http(s) URL, it's best to check {@code canOpenURL} first.

NOTE: For web URLs, the protocol ("http://", "https://") must be set accordingly!

@deprecated

static canOpenURL(url: string, callback: Function) #

Determine whether or not an installed app can handle a given URL.

You can use other URLs, like a location (e.g. "geo:37.484847,-122.148386"), a contact, -or any other URL that can be opened with {@code Intent.ACTION_VIEW}.

NOTE: For web URLs, the protocol ("http://", "https://") must be set accordingly!

@param URL the URL to open

@deprecated

static getInitialURL(callback: Function) #

If the app launch was triggered by an app link with {@code Intent.ACTION_VIEW}, -it will give the link url, otherwise it will give null

Refer http://developer.android.com/training/app-indexing/deep-linking.html#handling-intents

@deprecated

Examples #

Edit on GitHub
'use strict'; +If you're passing in a non-http(s) URL, it's best to check {@code canOpenURL} first.

NOTE: For web URLs, the protocol ("http://", "https://") must be set accordingly!

@deprecated

static canOpenURL(url: string, callback: Function) #

Determine whether or not an installed app can handle a given URL.

You can use other URLs, like a location (e.g. "geo:37.484847,-122.148386"), a contact, +or any other URL that can be opened with {@code Intent.ACTION_VIEW}.

NOTE: For web URLs, the protocol ("http://", "https://") must be set accordingly!

@param URL the URL to open

@deprecated

static getInitialURL(callback: Function) #

If the app launch was triggered by an app link with {@code Intent.ACTION_VIEW}, +it will give the link url, otherwise it will give null

Refer http://developer.android.com/training/app-indexing/deep-linking.html#handling-intents

@deprecated

Examples #

Edit on GitHub
'use strict'; var React = require('react-native'); var { @@ -106,7 +106,7 @@ it will give the link url, otherwise it will give null

Refer }, }); -module.exports = IntentAndroidExample;

© 2015 Facebook Inc.

InteractionManager #

Edit on GitHub

InteractionManager allows long-running work to be scheduled after any +InteractionManager – React Native | A framework for building native apps using React

InteractionManager #

Edit on GitHub

InteractionManager allows long-running work to be scheduled after any interactions/animations have completed. In particular, this allows JavaScript animations to run smoothly.

Applications can schedule tasks to run after interactions with the following:

InteractionManager.runAfterInteractions(() => { // ...long-running synchronous task... @@ -20,9 +20,9 @@ earlier.

By default, queued tasks are executed together in a loop in one tasks will only be executed until the deadline (in terms of js event loop run time) approaches, at which point execution will yield via setTimeout, allowing events such as touches to start interactions and block queued tasks -from executing, making apps more responsive.

Methods #

static runAfterInteractions(task: Task) #

Schedule a function to run after all interactions have completed.

static createInteractionHandle() #

Notify manager that an interaction has started.

static clearInteractionHandle(handle: Handle) #

Notify manager that an interaction has completed.

static setDeadline(deadline: number) #

A positive number will use setTimeout to schedule any tasks after the +from executing, making apps more responsive.

Methods #

static runAfterInteractions(task: Task) #

Schedule a function to run after all interactions have completed.

static createInteractionHandle() #

Notify manager that an interaction has started.

static clearInteractionHandle(handle: Handle) #

Notify manager that an interaction has completed.

static setDeadline(deadline: number) #

A positive number will use setTimeout to schedule any tasks after the eventLoopRunningTime hits the deadline value, otherwise all tasks will be -executed in one setImmediate batch (default).

Properties #

Events: CallExpression #

addListener: CallExpression #

© 2015 Facebook Inc.

JavaScript Environment #

Edit on GitHub

JavaScript Runtime #

When using React Native, you're going to be running your JavaScript code in two environments:

  • On iOS simulators and devices, Android emulators and devices React Native uses JavaScriptCore which is the JavaScript engine that powers Safari. On iOS JSC doesn't use JIT due to the absence of writable executable memory in iOS apps.
  • When using Chrome debugging, it runs all the JavaScript code within Chrome itself and communicates with native code via WebSocket. So you are using V8.

While both environments are very similar, you may end up hitting some inconsistencies. We're likely going to experiment with other JS engines in the future, so it's best to avoid relying on specifics of any runtime.

JavaScript Syntax Transformers #

Syntax transformers make writing code more enjoyable by allowing you to use new JavaScript syntax without having to wait for support on all interpreters.

As of version 0.5.0, React Native ships with the Babel JavaScript compiler. Check Babel documentation on its supported transformations for more details.

Here's a full list of React Native's enabled transformations.

ES5

  • Reserved Words: promise.catch(function() { });

ES6

ES7

© 2015 Facebook Inc.

JavaScript Environment #

Edit on GitHub

JavaScript Runtime #

When using React Native, you're going to be running your JavaScript code in two environments:

  • On iOS simulators and devices, Android emulators and devices React Native uses JavaScriptCore which is the JavaScript engine that powers Safari. On iOS JSC doesn't use JIT due to the absence of writable executable memory in iOS apps.
  • When using Chrome debugging, it runs all the JavaScript code within Chrome itself and communicates with native code via WebSocket. So you are using V8.

While both environments are very similar, you may end up hitting some inconsistencies. We're likely going to experiment with other JS engines in the future, so it's best to avoid relying on specifics of any runtime.

JavaScript Syntax Transformers #

Syntax transformers make writing code more enjoyable by allowing you to use new JavaScript syntax without having to wait for support on all interpreters.

As of version 0.5.0, React Native ships with the Babel JavaScript compiler. Check Babel documentation on its supported transformations for more details.

Here's a full list of React Native's enabled transformations.

ES5

  • Reserved Words: promise.catch(function() { });

ES6

ES7

Specific

  • JSX: <View style={{color: 'red'}} />
  • Flow: function foo(x: ?number): string {}

Polyfills #

Many standards functions are also available on all the supported JavaScript runtimes.

Browser

ES6

ES7

Specific

  • __DEV__
© 2016 Facebook Inc.

Known Issues #

Edit on GitHub

Devtools "React" Tab Does Not Work #

It's currently not possible to use the "React" tab in the devtools to inspect app widgets. This is due to a change in how the application scripts are evaluated in the devtools plugin; they are now run inside a Web Worker, and the plugin is unaware of this and so unable to communicate properly with React Native.

However, you can still use the Console feature of the devtools, and debugging JavaScript with breakpoints works too. To use the console, make sure to select the ⚙debuggerWorker.js entry in the devtools dropdown that by default is set to <top frame>.

Missing Modules and Native Views #

This is an initial release of React Native Android and therefore not all of the views present on iOS are released on Android. We are very much interested in the communities' feedback on the next set of modules and views for Open Source. Not all native views between iOS and Android have a 100% equivalent representation, here it will be necessary to use a counterpart eg using ProgressBar on Android in place of ActivityIndicator on iOS.

Our provisional plan for common views and modules includes:

Views #

Maps +Known Issues – React Native | A framework for building native apps using React

Known Issues #

Edit on GitHub

Devtools "React" Tab Does Not Work #

It's currently not possible to use the "React" tab in the devtools to inspect app widgets. This is due to a change in how the application scripts are evaluated in the devtools plugin; they are now run inside a Web Worker, and the plugin is unaware of this and so unable to communicate properly with React Native.

However, you can still use the Console feature of the devtools, and debugging JavaScript with breakpoints works too. To use the console, make sure to select the ⚙debuggerWorker.js entry in the devtools dropdown that by default is set to <top frame>.

Missing Modules and Native Views #

This is an initial release of React Native Android and therefore not all of the views present on iOS are released on Android. We are very much interested in the communities' feedback on the next set of modules and views for Open Source. Not all native views between iOS and Android have a 100% equivalent representation, here it will be necessary to use a counterpart eg using ProgressBar on Android in place of ActivityIndicator on iOS.

Our provisional plan for common views and modules includes:

Views #

Maps Modal Spinner (http://developer.android.com/guide/topics/ui/controls/spinner.html) -Slider (known as SeekBar)

Modules #

Camera Roll +Slider (known as SeekBar)

Modules #

Camera Roll Media -PushNotificationIOS

Some props are only supported on one platform #

There are properties that work on one platform only, either because they can inherently only be supported on that platform or because they haven't been implemented on the other platforms yet. All of these are annotated with @platform in JS docs and have a small badge next to them on the website. See e.g. Image.

Platform parity #

There are known cases where the APIs could be made more consistent across iOS and Android:

  • <ViewPagerAndroid> and <ScrollView pagingEnabled={true}> on iOS do a similar thing. We might want to unify them to <ViewPager>.
  • ActivityIndicator could render a native spinning indicator on both platforms (currently this is done using ActivityIndicatorIOS on iOS and ProgressBarAndroid on Android).
  • ProgressBar could render a horizontal progress bar on both platforms (on iOS this is ProgressViewIOS, on Android it's ProgressBarAndroid).

Using 3rd-party native modules #

There are many awesome 3rd-party modules: JS.coach

Adding these to your apps should be made simpler. Here's an example how this is done currently.

The overflow style property defaults to hidden and cannot be changed on Android #

This is a result of how Android rendering works. This feature is not being worked on as it would be a significant undertaking and there are many more important tasks.

Another issue with overflow: 'hidden' on Android: a view is not clipped by the parent's borderRadius even if the parent has overflow: 'hidden' enabled – the corners of the inner view will be visible outside of the rounded corners. This is only on Android; it works as expected on iOS. See a demo of the bug and the corresponding issue.

View shadows #

The shadow* view styles apply on iOS, and the elevation view prop is available on Android. Setting elevation on Android is equivalent to using the native elevation API, and has the same limitations (most significantly, it only works on Android 5.0+). Setting elevation on Android also affects the z-order for overlapping views.

Android M permissions #

The open source version of React Native doesn't yet support the Android M permission model.

Layout-only nodes on Android #

An optimization feature of the Android version of React Native is for views which only contribute to the layout to not have a native view, only their layout properties are propagated to their children views. This optimization is to provide stability in deep view hierarchies for React Native and is therefore enabled by default. Should you depend on a view being present or internal tests incorrectly detect a view is layout only it will be necessary to turn off this behavior. To do this, set collapsable to false as in this example:

<View collapsable={false}> +PushNotificationIOS

Some props are only supported on one platform #

There are properties that work on one platform only, either because they can inherently only be supported on that platform or because they haven't been implemented on the other platforms yet. All of these are annotated with @platform in JS docs and have a small badge next to them on the website. See e.g. Image.

Platform parity #

There are known cases where the APIs could be made more consistent across iOS and Android:

  • <ViewPagerAndroid> and <ScrollView pagingEnabled={true}> on iOS do a similar thing. We might want to unify them to <ViewPager>.
  • ActivityIndicator could render a native spinning indicator on both platforms (currently this is done using ActivityIndicatorIOS on iOS and ProgressBarAndroid on Android).
  • ProgressBar could render a horizontal progress bar on both platforms (on iOS this is ProgressViewIOS, on Android it's ProgressBarAndroid).

Using 3rd-party native modules #

There are many awesome 3rd-party modules: JS.coach

Adding these to your apps should be made simpler. Here's an example how this is done currently.

The overflow style property defaults to hidden and cannot be changed on Android #

This is a result of how Android rendering works. This feature is not being worked on as it would be a significant undertaking and there are many more important tasks.

Another issue with overflow: 'hidden' on Android: a view is not clipped by the parent's borderRadius even if the parent has overflow: 'hidden' enabled – the corners of the inner view will be visible outside of the rounded corners. This is only on Android; it works as expected on iOS. See a demo of the bug and the corresponding issue.

View shadows #

The shadow* view styles apply on iOS, and the elevation view prop is available on Android. Setting elevation on Android is equivalent to using the native elevation API, and has the same limitations (most significantly, it only works on Android 5.0+). Setting elevation on Android also affects the z-order for overlapping views.

Android M permissions #

The open source version of React Native doesn't yet support the Android M permission model.

Layout-only nodes on Android #

An optimization feature of the Android version of React Native is for views which only contribute to the layout to not have a native view, only their layout properties are propagated to their children views. This optimization is to provide stability in deep view hierarchies for React Native and is therefore enabled by default. Should you depend on a view being present or internal tests incorrectly detect a view is layout only it will be necessary to turn off this behavior. To do this, set collapsable to false as in this example:

<View collapsable={false}> ... -</View>

Memory issues with PNG images #

React Native Android depends on Fresco for loading and displaying images. Currently we have disabled downsampling because it is experimental, so you may run into memory issues when loading large PNG images.

react-native init hangs #

Try running react-native init with --verbose and see #2797 for common causes.

Text Input Border #

The text input has by default a border at the bottom of its view. This border has its padding set by the background image provided by the system, and it cannot be changed. Solutions to avoid this is to either not set height explicitly, case in which the system will take care of displaying the border in the correct position, or to not display the border by setting underlineColor to transparent.

© 2015 Facebook Inc.

LayoutAnimation #

Edit on GitHub

Automatically animates views to their new positions when the +LayoutAnimation – React Native | A framework for building native apps using React

LayoutAnimation #

Edit on GitHub

Automatically animates views to their new positions when the next layout happens.

A common way to use this API is to call LayoutAnimation.configureNext -before calling setState.

Methods #

static configureNext(config: Config, onAnimationDidEnd?: Function) #

Schedules an animation to happen on the next layout.

@param config Specifies animation properties:

  • duration in milliseconds
  • create, config for animating in new views (see Anim type)
  • update, config for animating views that have been updated +before calling setState.

Methods #

static configureNext(config: Config, onAnimationDidEnd?: Function) #

Schedules an animation to happen on the next layout.

@param config Specifies animation properties:

  • duration in milliseconds
  • create, config for animating in new views (see Anim type)
  • update, config for animating views that have been updated (see Anim type)

@param onAnimationDidEnd Called when the animation finished. Only supported on iOS. -@param onError Called on error. Only supported on iOS.

static create(duration: number, type, creationProp) #

Helper for creating a config for configureNext.

Properties #

Types: CallExpression #

Properties: CallExpression #

configChecker: CallExpression #

Presets: ObjectExpression #

easeInEaseOut: CallExpression #

linear: CallExpression #

spring: CallExpression #

© 2015 Facebook Inc.

Linking Libraries #

Edit on GitHub

Not every app uses all the native capabilities, and including the code to support +Linking Libraries – React Native | A framework for building native apps using React

Linking Libraries #

Edit on GitHub

Not every app uses all the native capabilities, and including the code to support all those features would impact the binary size... But we still want to make it easy to add these features whenever you need them.

With that in mind we exposed many of these features as independent static libraries.

For most of the libs it will be as simple as dragging two files, sometimes a third step will be necessary, but no more than that.

All the libraries we ship with React Native live on the Libraries folder in the root of the repository. Some of them are pure JavaScript, and you only need to require it. Other libraries also rely on some native code, in that case you'll have to add these files to your app, otherwise the app will throw an -error as soon as you try to use the library.

Here the few steps to link your libraries that contain native code #

Automatic linking #

"rnpm" is a community project that allows linking of native dependencies automatically:

Step 1 #

Install rnpm:

$ npm install rnpm -g

Note: rnpm requires node version 4.1 or higher

Step 2 #

Install a library with native dependencies:

$ npm install <library-with-native-dependencies> --save

Note: --save or --save-dev flag is very important for this step. rnpm will link -your libs based on dependencies and devDependencies in your package.json file.

Step 3 #

Link your native dependencies:

$ rnpm link

Done! All libraries with a native dependencies should be successfully linked to your iOS/Android project.

Manual linking #

Step 1 #

If the library has native code, there must be a .xcodeproj file inside it's +error as soon as you try to use the library.

Here the few steps to link your libraries that contain native code #

Automatic linking #

"rnpm" is a community project that allows linking of native dependencies automatically:

Step 1 #

Install rnpm:

$ npm install rnpm -g

Note: rnpm requires node version 4.1 or higher

Step 2 #

Install a library with native dependencies:

$ npm install <library-with-native-dependencies> --save

Note: --save or --save-dev flag is very important for this step. rnpm will link +your libs based on dependencies and devDependencies in your package.json file.

Step 3 #

Link your native dependencies:

$ rnpm link

Done! All libraries with a native dependencies should be successfully linked to your iOS/Android project.

Manual linking #

Step 1 #

If the library has native code, there must be a .xcodeproj file inside it's folder. Drag this file to your project on Xcode (usually under the Libraries group -on Xcode);

Step 2 #

Click on your main project file (the one that represents the .xcodeproj) +on Xcode);

Step 2 #

Click on your main project file (the one that represents the .xcodeproj) select Build Phases and drag the static library from the Products folder -inside the Library you are importing to Link Binary With Libraries

Step 3 #

Not every library will need this step, what you need to consider is:

Do I need to know the contents of the library at compile time?

What that means is, are you using this library on the native side or only in +inside the Library you are importing to Link Binary With Libraries

Step 3 #

Not every library will need this step, what you need to consider is:

Do I need to know the contents of the library at compile time?

What that means is, are you using this library on the native side or only in JavaScript? If you are only using it in JavaScript, you are good to go!

This step is not necessary for libraries that we ship with React Native with the exception of PushNotificationIOS and LinkingIOS.

In the case of the PushNotificationIOS for example, you have to call a method on the library from your AppDelegate every time a new push notification is @@ -19,7 +19,7 @@ received.

For that we need to know the library's headers. To achieve to your project's file, select Build Settings and search for Header Search Paths. There you should include the path to your library (if it has relevant files on subdirectories remember to make it recursive, like React on the -example).

© 2015 Facebook Inc.

Linking #

Edit on GitHub

Linking gives you a general interface to interact with both incoming -and outgoing app links.

Basic Usage #

Handling deep links #

If your app was launched from an external url registered to your app you can +Linking – React Native | A framework for building native apps using React

Linking #

Edit on GitHub

Linking gives you a general interface to interact with both incoming +and outgoing app links.

Basic Usage #

Handling deep links #

If your app was launched from an external url registered to your app you can access and handle it from any component you want with

componentDidMount() { - var url = Linking.getInitialURL().then(url) => { + var url = Linking.getInitialURL().then((url) => { if (url) { console.log('Initial url is: ' + url); } }).catch(err => console.error('An error occurred', err)); }

NOTE: For instructions on how to add support for deep linking on Android, refer Enabling Deep Links for App Content - Add Intent Filters for Your Deep Links.

NOTE: For iOS, in case you also want to listen to incoming app links during your app's -execution you'll need to add the following lines to you *AppDelegate.m:

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url +execution you'll need to add the following lines to you *AppDelegate.m:

#import "RCTLinkingManager.h" + +- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { - return [LinkingManager application:application openURL:url + return [RCTLinkingManager application:application openURL:url sourceApplication:sourceApplication annotation:annotation]; } @@ -19,7 +21,7 @@ execution you'll need to add the following lines to you *AppDelegate. - (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray * _Nullable))restorationHandler { - return [LinkingManager application:application + return [RCTLinkingManager application:application continueUserActivity:userActivity restorationHandler:restorationHandler]; }

And then on your React component you'll be able to listen to the events on @@ -31,18 +33,18 @@ execution you'll need to add the following lines to you *AppDelegate. }, _handleOpenURL(event) { console.log(event.url); -}

Note that this is only supported on iOS.

Opening external links #

To start the corresponding activity for a link (web URL, email, contact etc.), call

Linking.openURL(url).catch(err => console.error('An error occurred', err));

If you want to check if any installed app can handle a given URL beforehand you can call

Linking.canOpenURL(url).then(supported => { +}

Note that this is only supported on iOS.

Opening external links #

To start the corresponding activity for a link (web URL, email, contact etc.), call

Linking.openURL(url).catch(err => console.error('An error occurred', err));

If you want to check if any installed app can handle a given URL beforehand you can call

Linking.canOpenURL(url).then(supported => { if (!supported) { console.log('Can\'t handle url: ' + url); } else { return Linking.openURL(url); } -}).catch(err => console.error('An error occurred', err));

Methods #

static addEventListener(type: string, handler: Function) #

Add a handler to Linking changes by listening to the url event type -and providing the handler

@platform ios

static removeEventListener(type: string, handler: Function) #

Remove a handler by passing the url event type and the handler

@platform ios

static openURL(url: string) #

Try to open the given url with any of the installed apps.

You can use other URLs, like a location (e.g. "geo:37.484847,-122.148386"), a contact, +}).catch(err => console.error('An error occurred', err));

Methods #

static addEventListener(type: string, handler: Function) #

Add a handler to Linking changes by listening to the url event type +and providing the handler

@platform ios

static removeEventListener(type: string, handler: Function) #

Remove a handler by passing the url event type and the handler

@platform ios

static openURL(url: string) #

Try to open the given url with any of the installed apps.

You can use other URLs, like a location (e.g. "geo:37.484847,-122.148386"), a contact, or any other URL that can be opened with the installed apps.

NOTE: This method will fail if the system doesn't know how to open the specified URL. -If you're passing in a non-http(s) URL, it's best to check {@code canOpenURL} first.

NOTE: For web URLs, the protocol ("http://", "https://") must be set accordingly!

static canOpenURL(url: string) #

Determine whether or not an installed app can handle a given URL.

NOTE: For web URLs, the protocol ("http://", "https://") must be set accordingly!

NOTE: As of iOS 9, your app needs to provide the LSApplicationQueriesSchemes key -inside Info.plist.

@param URL the URL to open

static getInitialURL() #

If the app launch was triggered by an app link with, -it will give the link url, otherwise it will give null

NOTE: To support deep linking on Android, refer http://developer.android.com/training/app-indexing/deep-linking.html#handling-intents

© 2015 Facebook Inc.

LinkingIOS #

Edit on GitHub

NOTE: LinkingIOS is being deprecated. Use Linking instead.

LinkingIOS gives you a general interface to interact with both incoming -and outgoing app links.

Basic Usage #

Handling deep links #

If your app was launched from an external url registered to your app you can +LinkingIOS – React Native | A framework for building native apps using React

LinkingIOS #

Edit on GitHub

NOTE: LinkingIOS is being deprecated. Use Linking instead.

LinkingIOS gives you a general interface to interact with both incoming +and outgoing app links.

Basic Usage #

Handling deep links #

If your app was launched from an external url registered to your app you can access and handle it from any component you want with

componentDidMount() { var url = LinkingIOS.popInitialURL(); }

In case you also want to listen to incoming app links during your app's @@ -26,17 +26,17 @@ execution you'll need to add the following lines to you *AppDelegate. }, _handleOpenURL(event) { console.log(event.url); -}

Triggering App links #

To trigger an app link (browser, email or custom schemas), call

LinkingIOS.openURL(url)

If you want to check if any installed app can handle a given URL beforehand, call

LinkingIOS.canOpenURL(url, (supported) => { +}

Triggering App links #

To trigger an app link (browser, email or custom schemas), call

LinkingIOS.openURL(url)

If you want to check if any installed app can handle a given URL beforehand, call

LinkingIOS.canOpenURL(url, (supported) => { if (!supported) { AlertIOS.alert('Can\'t handle url: ' + url); } else { LinkingIOS.openURL(url); } -});

Methods #

static addEventListener(type: string, handler: Function) #

Add a handler to LinkingIOS changes by listening to the url event type -and providing the handler

@deprecated

static removeEventListener(type: string, handler: Function) #

Remove a handler by passing the url event type and the handler

@deprecated

static openURL(url: string) #

Try to open the given url with any of the installed apps.

@deprecated

static canOpenURL(url: string, callback: Function) #

Determine whether or not an installed app can handle a given URL. +});

Methods #

static addEventListener(type: string, handler: Function) #

Add a handler to LinkingIOS changes by listening to the url event type +and providing the handler

@deprecated

static removeEventListener(type: string, handler: Function) #

Remove a handler by passing the url event type and the handler

@deprecated

static openURL(url: string) #

Try to open the given url with any of the installed apps.

@deprecated

static canOpenURL(url: string, callback: Function) #

Determine whether or not an installed app can handle a given URL. The callback function will be called with bool supported as the only argument

NOTE: As of iOS 9, your app needs to provide the LSApplicationQueriesSchemes key -inside Info.plist.

@deprecated

static popInitialURL() #

If the app launch was triggered by an app link, it will pop the link url, -otherwise it will return null

@deprecated

© 2015 Facebook Inc.

Linux and Windows Support #

Edit on GitHub

NOTE: This guide focuses on Android development. You'll need a Mac to build iOS apps.

As React Native on iOS requires a Mac and most of the engineers at Facebook and contributors use Macs, support for OS X is a top priority. However, we would like to support developers using Linux and Windows too. We believe we'll get the best Linux and Windows support from people using these operating systems on a daily basis.

Therefore, Linux and Windows support for the development environment is an ongoing community responsibility. This can mean filing issues and submitting PRs, and we'll help review and merge them. We are looking forward to your contributions and appreciate your patience.

As of version 0.14 Android development with React native is mostly possible on Linux and Windows. You'll need to install Node.js 4.0 or newer. On Linux we recommend installing watchman, otherwise you might hit a node file watching bug.

What's missing on Windows #

On Windows the packager won't be started automatically when you run react-native run-android. You can start it manually using:

cd MyAwesomeApp -react-native start

If you hit a ERROR Watcher took too long to load on Windows, try increasing the timeout in this file (under your node_modules/react-native).

© 2015 Facebook Inc.

Linux and Windows Support #

Edit on GitHub

NOTE: This guide focuses on Android development. You'll need a Mac to build iOS apps.

As React Native on iOS requires a Mac and most of the engineers at Facebook and contributors use Macs, support for OS X is a top priority. However, we would like to support developers using Linux and Windows too. We believe we'll get the best Linux and Windows support from people using these operating systems on a daily basis.

Therefore, Linux and Windows support for the development environment is an ongoing community responsibility. This can mean filing issues and submitting PRs, and we'll help review and merge them. We are looking forward to your contributions and appreciate your patience.

As of version 0.14 Android development with React native is mostly possible on Linux and Windows. You'll need to install Node.js 4.0 or newer. On Linux we recommend installing watchman, otherwise you might hit a node file watching bug.

What's missing on Windows #

On Windows the packager won't be started automatically when you run react-native run-android. You can start it manually using:

cd MyAwesomeApp +react-native start

If you hit a ERROR Watcher took too long to load on Windows, try increasing the timeout in this file (under your node_modules/react-native).

© 2016 Facebook Inc.

ListView #

Edit on GitHub

ListView - A core component designed for efficient display of vertically +ListView – React Native | A framework for building native apps using React

ListView #

Edit on GitHub

ListView - A core component designed for efficient display of vertically scrolling lists of changing data. The minimal API is to create a ListView.DataSource, populate it with a simple array of data blobs, and instantiate a ListView component with that data source and a renderRow @@ -28,39 +28,43 @@ data source tells the ListView if it needs to re-render a row because the source data has changed - see ListViewDataSource for more details.

  • Rate-limited row rendering - By default, only one row is rendered per event-loop (customizable with the pageSize prop). This breaks up the work into smaller chunks to reduce the chance of dropping frames while -rendering rows.

  • Props #

    dataSource ListViewDataSource #

    initialListSize number #

    How many rows to render on initial component mount. Use this to make +rendering rows.

    Props #

    dataSource ListViewDataSource #

    initialListSize number #

    How many rows to render on initial component mount. Use this to make it so that the first screen worth of data appears at one time instead of -over the course of multiple frames.

    onChangeVisibleRows function #

    (visibleRows, changedRows) => void

    Called when the set of visible rows changes. visibleRows maps +over the course of multiple frames.

    onChangeVisibleRows function #

    (visibleRows, changedRows) => void

    Called when the set of visible rows changes. visibleRows maps { sectionID: { rowID: true }} for all the visible rows, and changedRows maps { sectionID: { rowID: true | false }} for the rows that have changed their visibility, with true indicating visible, and -false indicating the view has moved out of view.

    onEndReached function #

    Called when all rows have been rendered and the list has been scrolled +false indicating the view has moved out of view.

    onEndReached function #

    Called when all rows have been rendered and the list has been scrolled to within onEndReachedThreshold of the bottom. The native scroll -event is provided.

    onEndReachedThreshold number #

    Threshold in pixels for onEndReached.

    pageSize number #

    Number of rows to render per event loop.

    removeClippedSubviews bool #

    A performance optimization for improving scroll perf of +event is provided.

    onEndReachedThreshold number #

    Threshold in pixels (virtual, not physical) for calling onEndReached.

    pageSize number #

    Number of rows to render per event loop. Note: if your 'rows' are actually +cells, i.e. they don't span the full width of your view (as in the +ListViewGridLayoutExample), you should set the pageSize to be a multiple +of the number of cells per row, otherwise you're likely to see gaps at +the edge of the ListView as new pages are loaded.

    removeClippedSubviews bool #

    A performance optimization for improving scroll perf of large lists, used in conjunction with overflow: 'hidden' on the row -containers. This is enabled by default.

    renderFooter function #

    () => renderable

    The header and footer are always rendered (if these props are provided) +containers. This is enabled by default.

    renderFooter function #

    () => renderable

    The header and footer are always rendered (if these props are provided) on every render pass. If they are expensive to re-render, wrap them in StaticContainer or other mechanism as appropriate. Footer is always -at the bottom of the list, and header at the top, on every render pass.

    renderHeader function #

    renderRow function #

    (rowData, sectionID, rowID, highlightRow) => renderable

    Takes a data entry from the data source and its ids and should return +at the bottom of the list, and header at the top, on every render pass.

    renderHeader function #

    renderRow function #

    (rowData, sectionID, rowID, highlightRow) => renderable

    Takes a data entry from the data source and its ids and should return a renderable component to be rendered as the row. By default the data is exactly what was put into the data source, but it's also possible to provide custom extractors. ListView can be notified when a row is being highlighted by calling highlightRow function. The separators above and below will be hidden when a row is highlighted. The highlighted state of -a row can be reset by calling highlightRow(null).

    renderScrollComponent function #

    (props) => renderable

    A function that returns the scrollable component in which the list rows -are rendered. Defaults to returning a ScrollView with the given props.

    renderSectionHeader function #

    (sectionData, sectionID) => renderable

    If provided, a sticky header is rendered for this section. The sticky +a row can be reset by calling highlightRow(null).

    renderScrollComponent function #

    (props) => renderable

    A function that returns the scrollable component in which the list rows +are rendered. Defaults to returning a ScrollView with the given props.

    renderSectionHeader function #

    (sectionData, sectionID) => renderable

    If provided, a sticky header is rendered for this section. The sticky behavior means that it will scroll with the content at the top of the section until it reaches the top of the screen, at which point it will stick to the top until it is pushed off the screen by the next section -header.

    renderSeparator function #

    (sectionID, rowID, adjacentRowHighlighted) => renderable

    If provided, a renderable component to be rendered as the separator +header.

    renderSeparator function #

    (sectionID, rowID, adjacentRowHighlighted) => renderable

    If provided, a renderable component to be rendered as the separator below each row but not the last row if there is a section header below. Take a sectionID and rowID of the row above and whether its adjacent row -is highlighted.

    scrollRenderAheadDistance number #

    How early to start rendering rows before they come on screen, in -pixels.

    iosstickyHeaderIndices [number] #

    An array of child indices determining which children get docked to the +is highlighted.

    scrollRenderAheadDistance number #

    How early to start rendering rows before they come on screen, in +pixels.

    iosstickyHeaderIndices [number] #

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

    Examples #

    Edit on GitHub
    'use strict'; +with horizontal={true}.

    Examples #

    Edit on GitHub
    'use strict'; var React = require('react-native'); var { @@ -189,7 +193,7 @@ with horizontal={true}.

    },}); -module.exports = ListViewSimpleExample;
    © 2015 Facebook Inc.

    MapView #

    Edit on GitHub

    Props #

    onAnnotationPress function #

    Deprecated. Use annotation onFocus and onBlur instead.

    onRegionChange function #

    Callback that is called continuously when the user is dragging the map.

    onRegionChangeComplete function #

    Callback that is called once, when the user is done moving the map.

    pitchEnabled bool #

    When this property is set to true and a valid camera is associated +MapView – React Native | A framework for building native apps using React

    MapView #

    Edit on GitHub

    Props #

    onAnnotationPress function #

    Deprecated. Use annotation onFocus and onBlur instead.

    onRegionChange function #

    Callback that is called continuously when the user is dragging the map.

    onRegionChangeComplete function #

    Callback that is called once, when the user is done moving the map.

    pitchEnabled bool #

    When this property is set to true and a valid camera is associated with the map, the camera’s pitch angle is used to tilt the plane of the map. When this property is set to false, the camera’s pitch angle is ignored and the map is always displayed as if the user -is looking straight down onto it.

    region {latitude: number, longitude: number, latitudeDelta: number, longitudeDelta: number} #

    The region to be displayed by the map.

    The region is defined by the center coordinates and the span of -coordinates to display.

    rotateEnabled bool #

    When this property is set to true and a valid camera is associated with +is looking straight down onto it.

    region {latitude: number, longitude: number, latitudeDelta: number, longitudeDelta: number} #

    The region to be displayed by the map.

    The region is defined by the center coordinates and the span of +coordinates to display.

    rotateEnabled bool #

    When this property is set to true and a valid camera is associated with the map, the camera’s heading angle is used to rotate the plane of the map around its center point. When this property is set to false, the camera’s heading angle is ignored and the map is always oriented so -that true north is situated at the top of the map view

    scrollEnabled bool #

    If false the user won't be able to change the map region being displayed. -Default value is true.

    showsUserLocation bool #

    If true the app will ask for the user's location and display it on +that true north is situated at the top of the map view

    scrollEnabled bool #

    If false the user won't be able to change the map region being displayed. +Default value is true.

    showsUserLocation bool #

    If true the app will ask for the user's location and display it on the map. Default value is false.

    NOTE: on iOS, you need to add the NSLocationWhenInUseUsageDescription -key in Info.plist to enable geolocation, otherwise it will fail silently.

    style View#style #

    Used to style and layout the MapView. See StyleSheet.js and -ViewStylePropTypes.js for more info.

    zoomEnabled bool #

    If false the user won't be able to pinch/zoom the map. -Default value is true.

    androidactive bool #

    iosannotations [{latitude: number, longitude: number, animateDrop: bool, draggable: bool, onDragStateChange: function, onFocus: function, onBlur: function, title: string, subtitle: string, leftCalloutView: element, rightCalloutView: element, detailCalloutView: element, tintColor: [object Object], image: Image.propTypes.source, view: element, id: string, hasLeftCallout: deprecatedPropType( +key in Info.plist to enable geolocation, otherwise it will fail silently.

    style View#style #

    Used to style and layout the MapView. See StyleSheet.js and +ViewStylePropTypes.js for more info.

    zoomEnabled bool #

    If false the user won't be able to pinch/zoom the map. +Default value is true.

    androidactive bool #

    iosannotations [{latitude: number, longitude: number, animateDrop: bool, draggable: bool, onDragStateChange: function, onFocus: function, onBlur: function, title: string, subtitle: string, leftCalloutView: element, rightCalloutView: element, detailCalloutView: element, tintColor: [object Object], image: Image.propTypes.source, view: element, id: string, hasLeftCallout: deprecatedPropType( React.PropTypes.bool, 'Use `leftCalloutView` instead.' ), hasRightCallout: deprecatedPropType( @@ -24,12 +24,12 @@ Default value is true.

    #

    Map annotations with title/subtitle.

    iosfollowUserLocation bool #

    If true the map will follow the user's location whenever it changes. +)}] #

    Map annotations with title/subtitle.

    iosfollowUserLocation bool #

    If true the map will follow the user's location whenever it changes. Note that this has no effect unless showsUserLocation is enabled. -Default value is true.

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

    Insets for the map's legal label, originally at bottom left of the map. -See EdgeInsetsPropType.js for more information.

    iosmapType enum('standard', 'satellite', 'hybrid') #

    The map type to be displayed.

    • standard: standard road map (default)
    • satellite: satellite view
    • hybrid: satellite view with roads and points of interest overlaid

    iosmaxDelta number #

    Maximum size of area that can be displayed.

    iosminDelta number #

    Minimum size of area that can be displayed.

    iosoverlays [{coordinates: [{latitude: number, longitude: number}], lineWidth: number, strokeColor: [object Object], fillColor: [object Object], id: string}] #

    Map overlays

    iosshowsCompass bool #

    If false compass won't be displayed on the map. -Default value is true.

    iosshowsPointsOfInterest bool #

    If false points of interest won't be displayed on the map. -Default value is true.

    Examples #

    Edit on GitHub
    'use strict'; +Default value is true.

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

    Insets for the map's legal label, originally at bottom left of the map. +See EdgeInsetsPropType.js for more information.

    iosmapType enum('standard', 'satellite', 'hybrid') #

    The map type to be displayed.

    • standard: standard road map (default)
    • satellite: satellite view
    • hybrid: satellite view with roads and points of interest overlaid

    iosmaxDelta number #

    Maximum size of area that can be displayed.

    iosminDelta number #

    Minimum size of area that can be displayed.

    iosoverlays [{coordinates: [{latitude: number, longitude: number}], lineWidth: number, strokeColor: [object Object], fillColor: [object Object], id: string}] #

    Map overlays

    iosshowsCompass bool #

    If false compass won't be displayed on the map. +Default value is true.

    iosshowsPointsOfInterest bool #

    If false points of interest won't be displayed on the map. +Default value is true.

    Examples #

    Edit on GitHub
    'use strict'; var React = require('react-native'); var { @@ -420,7 +420,7 @@ exports.examples />; } }, -];
    © 2015 Facebook Inc.

    Modal #

    Edit on GitHub

    A Modal component covers the native view (e.g. UIViewController, Activity) +Modal – React Native | A framework for building native apps using React

    Modal #

    Edit on GitHub

    A Modal component covers the native view (e.g. UIViewController, Activity) that contains the React Native root.

    Use Modal in hybrid apps that embed React Native; Modal allows the portion of your app written in React Native to present content above the enclosing native view hierarchy.

    In apps written with React Native from the root view down, you should use Navigator instead of Modal. With a top-level Navigator, you have more control over how to present the modal scene over the rest of your app by using the -configureScene property.

    This component is only available in iOS at this time.

    Props #

    animated bool #

    onDismiss function #

    transparent bool #

    visible bool #

    Examples #

    Edit on GitHub
    'use strict'; +configureScene property.

    This component is only available in iOS at this time.

    Props #

    animated bool #

    onDismiss function #

    transparent bool #

    visible bool #

    Examples #

    Edit on GitHub
    'use strict'; var React = require('react-native'); var { @@ -162,7 +162,7 @@ exports.examples : { marginTop: 10, }, -});
    © 2015 Facebook Inc.

    Native UI Components #

    Edit on GitHub

    There are tons of native UI widgets out there ready to be used in the latest apps - some of them are part of the platform, others are available as third-party libraries, and still more might be in use in your very own portfolio. React Native has several of the most critical platform components already wrapped, like ScrollView and TextInput, but not all of them, and certainly not ones you might have written yourself for a previous app. Fortunately, it's quite easy to wrap up these existing components for seamless integration with your React Native application.

    Like the native module guide, this too is a more advanced guide that assumes you are somewhat familiar with Android SDK programming. This guide will show you how to build a native UI component, walking you through the implementation of a subset of the existing ImageViewcomponent available in the core React Native library.

    ImageView example #

    For this example we are going to walk through the implementation requirements to allow the use of ImageViews in JavaScript.

    Native views are created and manipulated by extending ViewManager or more commonly SimpleViewManager . A SimpleViewManager is convenient in this case because it applies common properties such as background color, opacity, and Flexbox layout.

    These subclasses are essentially singletons - only one instance of each is created by the bridge. They vend native views to the NativeViewHierarchyManager, which delegates back to them to set and update the properties of the views as necessary. The ViewManagers are also typically the delegates for the views, sending events back to JavaScript via the bridge.

    Vending a view is simple:

    1. Create the ViewManager subclass.
    2. Implement the createViewInstance method
    3. Expose view property setters using @ReactProp (or @ReactPropGroup) annotation
    4. Register the manager in createViewManagers of the applications package.
    5. Implement the JavaScript module

    1. Create the ViewManager subclass #

    In this example we create view manager class ReactImageManager that extends SimpleViewManager of type ReactImageView. ReactImageView is the type of object managed by the manager, this will be the custom native view. Name returned by getName is used to reference the native view type from JavaScript.

    ... +Native UI Components – React Native | A framework for building native apps using React

    Native UI Components #

    Edit on GitHub

    There are tons of native UI widgets out there ready to be used in the latest apps - some of them are part of the platform, others are available as third-party libraries, and still more might be in use in your very own portfolio. React Native has several of the most critical platform components already wrapped, like ScrollView and TextInput, but not all of them, and certainly not ones you might have written yourself for a previous app. Fortunately, it's quite easy to wrap up these existing components for seamless integration with your React Native application.

    Like the native module guide, this too is a more advanced guide that assumes you are somewhat familiar with Android SDK programming. This guide will show you how to build a native UI component, walking you through the implementation of a subset of the existing ImageViewcomponent available in the core React Native library.

    ImageView example #

    For this example we are going to walk through the implementation requirements to allow the use of ImageViews in JavaScript.

    Native views are created and manipulated by extending ViewManager or more commonly SimpleViewManager . A SimpleViewManager is convenient in this case because it applies common properties such as background color, opacity, and Flexbox layout.

    These subclasses are essentially singletons - only one instance of each is created by the bridge. They vend native views to the NativeViewHierarchyManager, which delegates back to them to set and update the properties of the views as necessary. The ViewManagers are also typically the delegates for the views, sending events back to JavaScript via the bridge.

    Vending a view is simple:

    1. Create the ViewManager subclass.
    2. Implement the createViewInstance method
    3. Expose view property setters using @ReactProp (or @ReactPropGroup) annotation
    4. Register the manager in createViewManagers of the applications package.
    5. Implement the JavaScript module

    1. Create the ViewManager subclass #

    In this example we create view manager class ReactImageManager that extends SimpleViewManager of type ReactImageView. ReactImageView is the type of object managed by the manager, this will be the custom native view. Name returned by getName is used to reference the native view type from JavaScript.

    ... public class ReactImageManager extends SimpleViewManager<ReactImageView> { @@ -7,10 +7,10 @@ public class ReactImageManager extends getName() { return REACT_CLASS; - }

    2. Implement method createViewInstance #

    Views are created in the createViewInstance method, the view should initialize itself in its default state, any properties will be set via a follow up call to updateView.

    @Override + }

    2. Implement method createViewInstance #

    Views are created in the createViewInstance method, the view should initialize itself in its default state, any properties will be set via a follow up call to updateView.

    @Override public ReactImageView createViewInstance(ThemedReactContext context) { return new ReactImageView(context, Fresco.newDraweeControllerBuilder(), mCallerContext); - }

    3. Expose view property setters using @ReactProp (or @ReactPropGroup) annotation #

    Properties that are to be reflected in JavaScript needs to be exposed as setter method annotated with @ReactProp (or @ReactPropGroup). Setter method should take view to be updated (of the current view type) as a first argument and property value as a second argument. Setter should be declared as a void method and should be public. Property type sent to JS is determined automatically based on the type of value argument of the setter. The following type of values are currently supported: boolean, int, float, double, String, Boolean, Integer, ReadableArray, ReadableMap.

    Annotation @ReactProp has one obligatory argument name of type String. Name assigned to the @ReactProp annotation linked to the setter method is used to reference the property on JS side.

    Except from name, @ReactProp annotation may take following optional arguments: defaultBoolean, defaultInt, defaultFloat. Those arguments should be of the corresponding primitive type (accordingly boolean, int, float) and the value provided will be passed to the setter method in case when the property that the setter is referencing has been removed from the component. Note that "default" values are only provided for primitive types, in case when setter is of some complex type, null will be provided as a default value in case when corresponding property gets removed.

    Setter declaration requirements for methods annotated with @ReactPropGroup are different than for @ReactProp, please refer to the @ReactPropGroup annotation class docs for more information about it.

    IMPORTANT! in ReactJS updating the property value will result in setter method call. Note that one of the ways we can update component is by removing properties that has been set before. In that case setter method will be called as well to notify view manager that property has changed. In that case "default" value will be provided (for primitive types "default" can value can be specified using defaultBoolean, defaultFloat, etc. arguments of @ReactProp annotation, for complex types setter will be called with value set to null).

    @ReactProp(name = "src") + }

    3. Expose view property setters using @ReactProp (or @ReactPropGroup) annotation #

    Properties that are to be reflected in JavaScript needs to be exposed as setter method annotated with @ReactProp (or @ReactPropGroup). Setter method should take view to be updated (of the current view type) as a first argument and property value as a second argument. Setter should be declared as a void method and should be public. Property type sent to JS is determined automatically based on the type of value argument of the setter. The following type of values are currently supported: boolean, int, float, double, String, Boolean, Integer, ReadableArray, ReadableMap.

    Annotation @ReactProp has one obligatory argument name of type String. Name assigned to the @ReactProp annotation linked to the setter method is used to reference the property on JS side.

    Except from name, @ReactProp annotation may take following optional arguments: defaultBoolean, defaultInt, defaultFloat. Those arguments should be of the corresponding primitive type (accordingly boolean, int, float) and the value provided will be passed to the setter method in case when the property that the setter is referencing has been removed from the component. Note that "default" values are only provided for primitive types, in case when setter is of some complex type, null will be provided as a default value in case when corresponding property gets removed.

    Setter declaration requirements for methods annotated with @ReactPropGroup are different than for @ReactProp, please refer to the @ReactPropGroup annotation class docs for more information about it.

    IMPORTANT! in ReactJS updating the property value will result in setter method call. Note that one of the ways we can update component is by removing properties that has been set before. In that case setter method will be called as well to notify view manager that property has changed. In that case "default" value will be provided (for primitive types "default" can value can be specified using defaultBoolean, defaultFloat, etc. arguments of @ReactProp annotation, for complex types setter will be called with value set to null).

    @ReactProp(name = "src") public void setSrc(ReactImageView view, @Nullable String src) { view.setSource(src); } @@ -23,15 +23,15 @@ public class ReactImageManager extends ReactProp(name = ViewProps.RESIZE_MODE) public void setResizeMode(ReactImageView view, @Nullable String resizeMode) { view.setScaleType(ImageResizeMode.toScaleType(resizeMode)); - }

    4. Register the ViewManager #

    The final Java step is to register the ViewManager to the application, this happens in a similar way to Native Modules, via the applications package member function createViewManagers.

    @Override + }

    4. Register the ViewManager #

    The final Java step is to register the ViewManager to the application, this happens in a similar way to Native Modules, via the applications package member function createViewManagers.

    @Override public List<ViewManager> createViewManagers( ReactApplicationContext reactContext) { return Arrays.<ViewManager>asList( new ReactImageManager() ); - }

    5. Implement the JavaScript module #

    The very final step is to create the JavaScript module that defines the interface layer between Java and JavaScript for the users of your new view. Much of the effort is handled by internal React code in Java and JavaScript and all that is left for you is to describe the propTypes.

    // ImageView.js + }

    5. Implement the JavaScript module #

    The very final step is to create the JavaScript module that defines the interface layer between Java and JavaScript for the users of your new view. Much of the effort is handled by internal React code in Java and JavaScript and all that is left for you is to describe the propTypes.

    // ImageView.js -var { requireNativeComponent, PropTypes } = require('react-native'); +import { requireNativeComponent, PropTypes } from 'react-native'; var iface = { name: 'ImageView', @@ -42,7 +42,7 @@ public class ReactImageManager extends }, }; -module.exports = requireNativeComponent('RCTImageView', iface);

    requireNativeComponent commonly takes two parameters, the first is the name of the native view and the second is an object that describes the component interface. The component interface should declare a friendly name for use in debug messages and must declare the propTypes reflected by the Native View. The propTypes are used for checking the validity of a user's use of the native view. Note that if you need your JavaScript component to do more than just specify a name and propTypes, like do custom event handling, you can wrap the native component in a normal react component. In that case, you want to pass in the wrapper component instead of iface to requireNativeComponent. This is illustrated in the MyCustomView example below.

    Events #

    So now we know how to expose native view components that we can control easily from JS, but how do we deal with events from the user, like pinch-zooms or panning? When a native event occurs the native code should issue an event to the JavaScript representation of the View, and the two views are linked with the value returned from the getId() method.

    class MyCustomView extends View { +module.exports = requireNativeComponent('RCTImageView', iface);

    requireNativeComponent commonly takes two parameters, the first is the name of the native view and the second is an object that describes the component interface. The component interface should declare a friendly name for use in debug messages and must declare the propTypes reflected by the Native View. The propTypes are used for checking the validity of a user's use of the native view. Note that if you need your JavaScript component to do more than just specify a name and propTypes, like do custom event handling, you can wrap the native component in a normal react component. In that case, you want to pass in the wrapper component instead of iface to requireNativeComponent. This is illustrated in the MyCustomView example below.

    Events #

    So now we know how to expose native view components that we can control easily from JS, but how do we deal with events from the user, like pinch-zooms or panning? When a native event occurs the native code should issue an event to the JavaScript representation of the View, and the two views are linked with the value returned from the getId() method.

    class MyCustomView extends View { ... public void onReceiveNativeEvent() { WritableMap event = Arguments.createMap(); @@ -79,7 +79,7 @@ MyCustomView.propTypes var RCTMyCustomView = requireNativeComponent(`RCTMyCustomView`, MyCustomView, { nativeOnly: {onChange: true} -});

    Note the use of nativeOnly above. Sometimes you'll have some special properties that you need to expose for the native component, but don't actually want them as part of the API for the associated React component. For example, Switch has a custom onChange handler for the raw native event, and exposes an onValueChange handler property that is invoked with just the boolean value rather than the raw event (similar to onChangeMessage in the example above). Since you don't want these native only properties to be part of the API, you don't want to put them in propTypes, but if you don't you'll get an error. The solution is simply to call them out via the nativeOnly option.

    © 2015 Facebook Inc.

    Native UI Components #

    Edit on GitHub

    There are tons of native UI widgets out there ready to be used in the latest apps - some of them are part of the platform, others are available as third-party libraries, and still more might be in use in your very own portfolio. React Native has several of the most critical platform components already wrapped, like ScrollView and TextInput, but not all of them, and certainly not ones you might have written yourself for a previous app. Fortunately, it's quite easy to wrap up these existing components for seamless integration with your React Native application.

    Like the native module guide, this too is a more advanced guide that assumes you are somewhat familiar with iOS programming. This guide will show you how to build a native UI component, walking you through the implementation of a subset of the existing MapView component available in the core React Native library.

    iOS MapView example #

    Let's say we want to add an interactive Map to our app - might as well use MKMapView, we just need to make it usable from JavaScript.

    Native views are created and manipulated by subclasses of RCTViewManager. These subclasses are similar in function to view controllers, but are essentially singletons - only one instance of each is created by the bridge. They vend native views to the RCTUIManager, which delegates back to them to set and update the properties of the views as necessary. The RCTViewManagers are also typically the delegates for the views, sending events back to JavaScript via the bridge.

    Vending a view is simple:

    • Create the basic subclass.
    • Add the RCT_EXPORT_MODULE() marker macro.
    • Implement the -(UIView *)view method
    // RCTMapManager.m +Native UI Components – React Native | A framework for building native apps using React

    Native UI Components #

    Edit on GitHub

    There are tons of native UI widgets out there ready to be used in the latest apps - some of them are part of the platform, others are available as third-party libraries, and still more might be in use in your very own portfolio. React Native has several of the most critical platform components already wrapped, like ScrollView and TextInput, but not all of them, and certainly not ones you might have written yourself for a previous app. Fortunately, it's quite easy to wrap up these existing components for seamless integration with your React Native application.

    Like the native module guide, this too is a more advanced guide that assumes you are somewhat familiar with iOS programming. This guide will show you how to build a native UI component, walking you through the implementation of a subset of the existing MapView component available in the core React Native library.

    iOS MapView example #

    Let's say we want to add an interactive Map to our app - might as well use MKMapView, we just need to make it usable from JavaScript.

    Native views are created and manipulated by subclasses of RCTViewManager. These subclasses are similar in function to view controllers, but are essentially singletons - only one instance of each is created by the bridge. They vend native views to the RCTUIManager, which delegates back to them to set and update the properties of the views as necessary. The RCTViewManagers are also typically the delegates for the views, sending events back to JavaScript via the bridge.

    Vending a view is simple:

    • Create the basic subclass.
    • Add the RCT_EXPORT_MODULE() marker macro.
    • Implement the -(UIView *)view method
    // RCTMapManager.m #import <MapKit/MapKit.h> #import "RCTViewManager.h" @@ -17,14 +17,13 @@ @end

    Then you just need a little bit of JavaScript to make this a usable React component:

    // MapView.js -var { requireNativeComponent } = require('react-native'); +import { requireNativeComponent } from 'react-native'; // requireNativeComponent automatically resolves this to "RCTMapManager" -module.exports = requireNativeComponent('RCTMap', null);

    This is now a fully-functioning native map view component in JavaScript, complete with pinch-zoom and other native gesture support. We can't really control it from JavaScript yet, though :(

    Properties #

    The first thing we can do to make this component more usable is to bridge over some native properties. Let's say we want to be able to disable pitch control and specify the visible region. Disabling pitch is a simple boolean, so we add this one line:

    // RCTMapManager.m +module.exports = requireNativeComponent('RCTMap', null);

    This is now a fully-functioning native map view component in JavaScript, complete with pinch-zoom and other native gesture support. We can't really control it from JavaScript yet, though :(

    Properties #

    The first thing we can do to make this component more usable is to bridge over some native properties. Let's say we want to be able to disable pitch control and specify the visible region. Disabling pitch is a simple boolean, so we add this one line:

    // RCTMapManager.m RCT_EXPORT_VIEW_PROPERTY(pitchEnabled, BOOL)

    Note that we explicitly specify the type as BOOL - React Native uses RCTConvert under the hood to convert all sorts of different data types when talking over the bridge, and bad values will show convenient "RedBox" errors to let you know there is an issue ASAP. When things are straightforward like this, the whole implementation is taken care of for you by this macro.

    Now to actually disable pitch, we set the property in JS:

    // MyApp.js <MapView pitchEnabled={false} />

    This isn't very well documented though - in order to know what properties are available and what values they accept, the client of your new component needs to dig through the Objective-C code. To make this better, let's make a wrapper component and document the interface with React PropTypes:

    // MapView.js -var React = require('react-native'); -var { requireNativeComponent } = React; +import React, { requireNativeComponent } from 'react-native'; class MapView extends React.Component { render() { @@ -128,7 +127,7 @@ MapView.propTypes return <MapView region={region} />; }

    Here you can see that the shape of the region is explicit in the JS documentation - ideally we could codegen some of this stuff, but that's not happening yet.

    Sometimes you'll have some special properties that you need to expose for the native component, but don't actually want them as part of the API for the associated React component. For example, Switch has a custom onChange handler for the raw native event, and exposes an onValueChange handler property that is invoked with just the boolean value rather than the raw event. Since you don't want these native only properties to be part of the API, you don't want to put them in propTypes, but if you don't you'll get an error. The solution is simply to call them out via the nativeOnly option, e.g.

    var RCTSwitch = requireNativeComponent('RCTSwitch', Switch, { nativeOnly: { onChange: true } -});

    Events #

    So now we have a native map component that we can control easily from JS, but how do we deal with events from the user, like pinch-zooms or panning to change the visible region? The key is to make the RCTMapManager a delegate for all the views it vends, and forward the events to JS via the event dispatcher. This looks like so (simplified from the full implementation):

    // RCTMapManager.m +});

    Events #

    So now we have a native map component that we can control easily from JS, but how do we deal with events from the user, like pinch-zooms or panning to change the visible region? The key is to make the RCTMapManager a delegate for all the views it vends, and forward the events to JS via the event dispatcher. This looks like so (simplified from the full implementation):

    // RCTMapManager.m #import "RCTMapManager.h" @@ -189,9 +188,10 @@ MapView.propTypes : React.PropTypes.func, ... -};

    Styles #

    Since all our native react views are subclasses of UIView, most style attributes will work like you would expect out of the box. Some components will want a default style, however, for example UIDatePicker which is a fixed size. This default style is important for the layout algorithm to work as expected, but we also want to be able to override the default style when using the component. DatePickerIOS does this by wrapping the native component in an extra view, which has flexible styling, and using a fixed style (which is generated with constants passed in from native) on the inner native component:

    // DatePickerIOS.ios.js +};

    Styles #

    Since all our native react views are subclasses of UIView, most style attributes will work like you would expect out of the box. Some components will want a default style, however, for example UIDatePicker which is a fixed size. This default style is important for the layout algorithm to work as expected, but we also want to be able to override the default style when using the component. DatePickerIOS does this by wrapping the native component in an extra view, which has flexible styling, and using a fixed style (which is generated with constants passed in from native) on the inner native component:

    // DatePickerIOS.ios.js -var RCTDatePickerIOSConsts = require('react-native').UIManager.RCTDatePicker.Constants; +import { UIManager } from 'react-native'; +var RCTDatePickerIOSConsts = UIManager.RCTDatePicker.Constants; ... render: function() { return ( @@ -227,7 +227,7 @@ MapView.propTypes "datetime": @(UIDatePickerModeDateAndTime), } }; -}

    This guide covered many of the aspects of bridging over custom native components, but there is even more you might need to consider, such as custom hooks for inserting and laying out subviews. If you want to go even deeper, check out the actual RCTMapManager and other components in the source code.

    © 2015 Facebook Inc.

    Native Modules #

    Edit on GitHub

    Sometimes an app needs access to a platform API that React Native doesn't have a corresponding module for yet. Maybe you want to reuse some existing Java code without having to reimplement it in JavaScript, or write some high performance, multi-threaded code such as for image processing, a database, or any number of advanced extensions.

    We designed React Native such that it is possible for you to write real native code and have access to the full power of the platform. This is a more advanced feature and we don't expect it to be part of the usual development process, however it is essential that it exists. If React Native doesn't support a native feature that you need, you should be able to build it yourself.

    The Toast Module #

    This guide will use the Toast example. Let's say we would like to be able to create a toast message from JavaScript.

    We start by creating a native module. A native module is a Java class that usually extends the ReactContextBaseJavaModule class and implements the functionality required by the JavaScript. Our goal here is to be able to write ToastAndroid.show('Awesome', ToastAndroid.SHORT); from JavaScript to display a short toast on the screen.

    package com.facebook.react.modules.toast; +Native Modules – React Native | A framework for building native apps using React

    Native Modules #

    Edit on GitHub

    Sometimes an app needs access to a platform API that React Native doesn't have a corresponding module for yet. Maybe you want to reuse some existing Java code without having to reimplement it in JavaScript, or write some high performance, multi-threaded code such as for image processing, a database, or any number of advanced extensions.

    We designed React Native such that it is possible for you to write real native code and have access to the full power of the platform. This is a more advanced feature and we don't expect it to be part of the usual development process, however it is essential that it exists. If React Native doesn't support a native feature that you need, you should be able to build it yourself.

    The Toast Module #

    This guide will use the Toast example. Let's say we would like to be able to create a toast message from JavaScript.

    We start by creating a native module. A native module is a Java class that usually extends the ReactContextBaseJavaModule class and implements the functionality required by the JavaScript. Our goal here is to be able to write ToastAndroid.show('Awesome', ToastAndroid.SHORT); from JavaScript to display a short toast on the screen.

    package com.facebook.react.modules.toast; import android.widget.Toast; @@ -30,14 +30,14 @@ public class ToastModule extends }

    To expose a method to JavaScript a Java method must be annotated using @ReactMethod. The return type of bridge methods is always void. React Native bridge is asynchronous, so the only way to pass a result to JavaScript is by using callbacks or emitting events (see below).

    @ReactMethod public void show(String message, int duration) { Toast.makeText(getReactApplicationContext(), message, duration).show(); - }

    Argument Types #

    The following argument types are supported for methods annotated with @ReactMethod and they directly map to their JavaScript equivalents

    Boolean -> Bool + }

    Argument Types #

    The following argument types are supported for methods annotated with @ReactMethod and they directly map to their JavaScript equivalents

    Boolean -> Bool Integer -> Number Double -> Number Float -> Number String -> String Callback -> function ReadableMap -> Object -ReadableArray -> Array

    Read more about ReadableMap and ReadableArray

    Register the Module #

    The last step within Java is to register the Module; this happens in the createNativeModules of your apps package. If a module is not registered it will not be available from JavaScript.

    class AnExampleReactPackage implements ReactPackage { +ReadableArray -> Array

    Read more about ReadableMap and ReadableArray

    Register the Module #

    The last step within Java is to register the Module; this happens in the createNativeModules of your apps package. If a module is not registered it will not be available from JavaScript.

    class AnExampleReactPackage implements ReactPackage { ... @@ -62,10 +62,10 @@ ReadableArray - * 2. int duration: The duration of the toast. May be ToastAndroid.SHORT or * ToastAndroid.LONG */ -var { NativeModules } = require('react-native'); -module.exports = NativeModules.ToastAndroid;

    Now, from your other JavaScript file you can call the method like this:

    var ToastAndroid = require('./ToastAndroid'); +import { NativeModules } from 'react-native'; +module.exports = NativeModules.ToastAndroid;

    Now, from your other JavaScript file you can call the method like this:

    import ToastAndroid from './ToastAndroid'; -ToastAndroid.show('Awesome', ToastAndroid.SHORT);

    Beyond Toasts #

    Callbacks #

    Native modules also support a special kind of argument - a callback. In most cases it is used to provide the function call result to JavaScript.

    public class UIManagerModule extends ReactContextBaseJavaModule { +ToastAndroid.show('Awesome', ToastAndroid.SHORT);

    Beyond Toasts #

    Callbacks #

    Native modules also support a special kind of argument - a callback. In most cases it is used to provide the function call result to JavaScript.

    public class UIManagerModule extends ReactContextBaseJavaModule { ... @@ -96,7 +96,7 @@ ToastAndroid.(x, y, width, height) => { console.log(x + ':' + y + ':' + width + ':' + height); } -);

    A native module is supposed to invoke its callback only once. It can, however, store the callback and invoke it later.

    It is very important to highlight that the callback is not invoked immediately after the native function completes - remember that bridge communication is asynchronous, and this too is tied to the run loop.

    Promises #

    Native modules can also fulfill a promise, which can simplify your code, especially when using ES2016's async/await syntax. When the last parameter of a bridged native method is a Promise, its corresponding JS method will return a JS Promise object.

    Refactoring the above code to use a promise instead of callbacks looks like this:

    public class UIManagerModule extends ReactContextBaseJavaModule { +);

    A native module is supposed to invoke its callback only once. It can, however, store the callback and invoke it later.

    It is very important to highlight that the callback is not invoked immediately after the native function completes - remember that bridge communication is asynchronous, and this too is tied to the run loop.

    Promises #

    Native modules can also fulfill a promise, which can simplify your code, especially when using ES2016's async/await syntax. When the last parameter of a bridged native method is a Promise, its corresponding JS method will return a JS Promise object.

    Refactoring the above code to use a promise instead of callbacks looks like this:

    public class UIManagerModule extends ReactContextBaseJavaModule { ... @@ -136,7 +136,7 @@ ToastAndroid.} } -measureLayout();

    Threading #

    Native modules should not have any assumptions about what thread they are being called on, as the current assignment is subject to change in the future. If a blocking call is required, the heavy work should be dispatched to an internally managed worker thread, and any callbacks distributed from there.

    Sending Events to JavaScript #

    Native modules can signal events to JavaScript without being invoked directly. The easiest way to do this is to use the RCTDeviceEventEmitter which can be obtained from the ReactContext as in the code snippet below.

    ... +measureLayout();

    Threading #

    Native modules should not have any assumptions about what thread they are being called on, as the current assignment is subject to change in the future. If a blocking call is required, the heavy work should be dispatched to an internally managed worker thread, and any callbacks distributed from there.

    Sending Events to JavaScript #

    Native modules can signal events to JavaScript without being invoked directly. The easiest way to do this is to use the RCTDeviceEventEmitter which can be obtained from the ReactContext as in the code snippet below.

    ... private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) { @@ -147,7 +147,7 @@ private void sendEvent... WritableMap params = Arguments.createMap(); ... -sendEvent(reactContext, "keyboardWillShow", params);

    JavaScript modules can then register to receive events by addListenerOn using the Subscribable mixin

    var { DeviceEventEmitter } = require('react-native'); +sendEvent(reactContext, "keyboardWillShow", params);

    JavaScript modules can then register to receive events by addListenerOn using the Subscribable mixin

    import { DeviceEventEmitter } from 'react-native'; ... var ScrollResponderMixin = { @@ -170,7 +170,7 @@ componentWillMount: // handle event. }); } -...

    Getting activity result from startActivityForResult #

    You'll need to listen to onActivityResult if you want to get results from an activity you started with startActivityForResult. To to do this, the module must implement ActivityEventListener. Then, you need to register a listener in the module's constructor,

    reactContext.addActivityEventListener(this);

    Now you can listen to onActivityResult by implementing the following method:

    @Override +...

    Getting activity result from startActivityForResult #

    You'll need to listen to onActivityResult if you want to get results from an activity you started with startActivityForResult. To to do this, the module must implement ActivityEventListener. Then, you need to register a listener in the module's constructor,

    reactContext.addActivityEventListener(this);

    Now you can listen to onActivityResult by implementing the following method:

    @Override public void onActivityResult(final int requestCode, final int resultCode, final Intent intent) { // Your logic here }

    We will implement a simple image picker to demonstrate this. The image picker will expose the method pickImage to JavaScript, which will return the path of the image when called.

    public class ImagePickerModule extends ReactContextBaseJavaModule implements ActivityEventListener { @@ -242,7 +242,7 @@ public void onActivityResult} } } -}

    Listening to LifeCycle events #

    Listening to the activity's LifeCycle events such as onResume, onPause etc. is very similar to how we implemented ActivityEventListener. The module must implement ActivityEventListener. Then, you need to register a listener in the module's constructor,

    reactContext.addLifecycleEventListener(this);

    Now you can listen to the activity's LifeCycle events by implementing the following methods:

    @Override +}

    Listening to LifeCycle events #

    Listening to the activity's LifeCycle events such as onResume, onPause etc. is very similar to how we implemented ActivityEventListener. The module must implement LifecycleEventListener. Then, you need to register a listener in the module's constructor,

    reactContext.addLifecycleEventListener(this);

    Now you can listen to the activity's LifeCycle events by implementing the following methods:

    @Override public void onHostResume() { // Actvity `onResume` } @@ -255,7 +255,7 @@ public void onHostPauseonHostDestroy() { // Actvity `onDestroy` -}
    © 2015 Facebook Inc.

    Native Modules #

    Edit on GitHub

    Sometimes an app needs access to platform API, and React Native doesn't have a corresponding module yet. Maybe you want to reuse some existing Objective-C, Swift or C++ code without having to reimplement it in JavaScript, or write some high performance, multi-threaded code such as for image processing, a database, or any number of advanced extensions.

    We designed React Native such that it is possible for you to write real native code and have access to the full power of the platform. This is a more advanced feature and we don't expect it to be part of the usual development process, however it is essential that it exists. If React Native doesn't support a native feature that you need, you should be able to build it yourself.

    This is a more advanced guide that shows how to build a native module. It assumes the reader knows Objective-C or Swift and core libraries (Foundation, UIKit).

    iOS Calendar Module Example #

    This guide will use the iOS Calendar API example. Let's say we would like to be able to access the iOS calendar from JavaScript.

    A native module is just an Objective-C class that implements the RCTBridgeModule protocol. If you are wondering, RCT is an abbreviation of ReaCT.

    // CalendarManager.h +Native Modules – React Native | A framework for building native apps using React

    Native Modules #

    Edit on GitHub

    Sometimes an app needs access to platform API, and React Native doesn't have a corresponding module yet. Maybe you want to reuse some existing Objective-C, Swift or C++ code without having to reimplement it in JavaScript, or write some high performance, multi-threaded code such as for image processing, a database, or any number of advanced extensions.

    We designed React Native such that it is possible for you to write real native code and have access to the full power of the platform. This is a more advanced feature and we don't expect it to be part of the usual development process, however it is essential that it exists. If React Native doesn't support a native feature that you need, you should be able to build it yourself.

    This is a more advanced guide that shows how to build a native module. It assumes the reader knows Objective-C or Swift and core libraries (Foundation, UIKit).

    iOS Calendar Module Example #

    This guide will use the iOS Calendar API example. Let's say we would like to be able to access the iOS calendar from JavaScript.

    A native module is just an Objective-C class that implements the RCTBridgeModule protocol. If you are wondering, RCT is an abbreviation of ReaCT.

    // CalendarManager.h #import "RCTBridgeModule.h" @interface CalendarManager : NSObject <RCTBridgeModule> @@ -10,8 +10,9 @@ @end

    React Native will not expose any methods of CalendarManager to JavaScript unless explicitly told to. This is done using the RCT_EXPORT_METHOD() macro:

    RCT_EXPORT_METHOD(addEvent:(NSString *)name location:(NSString *)location) { RCTLogInfo(@"Pretending to create an event %@ at %@", name, location); -}

    Now, from your JavaScript file you can call the method like this:

    var CalendarManager = require('react-native').NativeModules.CalendarManager; -CalendarManager.addEvent('Birthday Party', '4 Privet Drive, Surrey');

    NOTE: JavaScript method names

    The name of the method exported to JavaScript is the native method's name up to the first colon. React Native also defines a macro called RCT_REMAP_METHOD() to specify the JavaScript method's name. This is useful when multiple native methods are the same up to the first colon and would have conflicting JavaScript names.

    The return type of bridge methods is always void. React Native bridge is asynchronous, so the only way to pass a result to JavaScript is by using callbacks or emitting events (see below).

    Argument Types #

    RCT_EXPORT_METHOD supports all standard JSON object types, such as:

    • string (NSString)
    • number (NSInteger, float, double, CGFloat, NSNumber)
    • boolean (BOOL, NSNumber)
    • array (NSArray) of any types from this list
    • map (NSDictionary) with string keys and values of any type from this list
    • function (RCTResponseSenderBlock)

    But it also works with any type that is supported by the RCTConvert class (see RCTConvert for details). The RCTConvert helper functions all accept a JSON value as input and map it to a native Objective-C type or class.

    In our CalendarManager example, we need to pass the event date to the native method. We can't send JavaScript Date objects over the bridge, so we need to convert the date to a string or number. We could write our native function like this:

    RCT_EXPORT_METHOD(addEvent:(NSString *)name location:(NSString *)location date:(NSNumber *)secondsSinceUnixEpoch) +}

    Now, from your JavaScript file you can call the method like this:

    import { NativeModules } from 'react-native'; +var CalendarManager = NativeModules.CalendarManager; +CalendarManager.addEvent('Birthday Party', '4 Privet Drive, Surrey');

    NOTE: JavaScript method names

    The name of the method exported to JavaScript is the native method's name up to the first colon. React Native also defines a macro called RCT_REMAP_METHOD() to specify the JavaScript method's name. This is useful when multiple native methods are the same up to the first colon and would have conflicting JavaScript names.

    The return type of bridge methods is always void. React Native bridge is asynchronous, so the only way to pass a result to JavaScript is by using callbacks or emitting events (see below).

    Argument Types #

    RCT_EXPORT_METHOD supports all standard JSON object types, such as:

    • string (NSString)
    • number (NSInteger, float, double, CGFloat, NSNumber)
    • boolean (BOOL, NSNumber)
    • array (NSArray) of any types from this list
    • map (NSDictionary) with string keys and values of any type from this list
    • function (RCTResponseSenderBlock)

    But it also works with any type that is supported by the RCTConvert class (see RCTConvert for details). The RCTConvert helper functions all accept a JSON value as input and map it to a native Objective-C type or class.

    In our CalendarManager example, we need to pass the event date to the native method. We can't send JavaScript Date objects over the bridge, so we need to convert the date to a string or number. We could write our native function like this:

    RCT_EXPORT_METHOD(addEvent:(NSString *)name location:(NSString *)location date:(NSNumber *)secondsSinceUnixEpoch) { NSDate *date = [RCTConvert NSDate:secondsSinceUnixEpoch]; }

    or like this:

    RCT_EXPORT_METHOD(addEvent:(NSString *)name location:(NSString *)location date:(NSString *)ISO8601DateString) @@ -31,7 +32,7 @@ CalendarManager.: '4 Privet Drive, Surrey', time: date.toTime(), description: '...' -})

    NOTE: About array and map

    Objective-C doesn't provide any guarantees about the types of values in these structures. Your native module might expect an array of strings, but if JavaScript calls your method with an array containing numbers and strings, you'll get an NSArray containing a mix of NSNumber and NSString. For arrays, RCTConvert provides some typed collections you can use in your method declaration, such as NSStringArray, or UIColorArray. For maps, it is the developer's responsibility to check the value types individually by manually calling RCTConvert helper methods.

    Callbacks #

    WARNING

    This section is more experimental than others because we don't have a solid set of best practices around callbacks yet.

    Native modules also supports a special kind of argument- a callback. In most cases it is used to provide the function call result to JavaScript.

    RCT_EXPORT_METHOD(findEvents:(RCTResponseSenderBlock)callback) +})

    NOTE: About array and map

    Objective-C doesn't provide any guarantees about the types of values in these structures. Your native module might expect an array of strings, but if JavaScript calls your method with an array containing numbers and strings, you'll get an NSArray containing a mix of NSNumber and NSString. For arrays, RCTConvert provides some typed collections you can use in your method declaration, such as NSStringArray, or UIColorArray. For maps, it is the developer's responsibility to check the value types individually by manually calling RCTConvert helper methods.

    Callbacks #

    WARNING

    This section is more experimental than others because we don't have a solid set of best practices around callbacks yet.

    Native modules also supports a special kind of argument- a callback. In most cases it is used to provide the function call result to JavaScript.

    RCT_EXPORT_METHOD(findEvents:(RCTResponseSenderBlock)callback) { NSArray *events = ... callback(@[[NSNull null], events]); @@ -41,7 +42,7 @@ CalendarManager.} else { this.setState({events: events}); } -})

    A native module is supposed to invoke its callback only once. It can, however, store the callback and invoke it later. This pattern is often used to wrap iOS APIs that require delegates. See RCTAlertManager for an example.

    If you want to pass error-like objects to JavaScript, use RCTMakeError from RCTUtils.h. Right now this just passes an Error-shaped dictionary to JavaScript, but we would like to automatically generate real JavaScript Error objects in the future.

    Promises #

    Native modules can also fulfill a promise, which can simplify your code, especially when using ES2016's async/await syntax. When the last parameters of a bridged native method are an RCTPromiseResolveBlock and RCTPromiseRejectBlock, its corresponding JS method will return a JS Promise object.

    Refactoring the above code to use a promise instead of callbacks looks like this:

    RCT_REMAP_METHOD(findEvents, +})

    A native module is supposed to invoke its callback only once. It can, however, store the callback and invoke it later. This pattern is often used to wrap iOS APIs that require delegates. See RCTAlertManager for an example.

    If you want to pass error-like objects to JavaScript, use RCTMakeError from RCTUtils.h. Right now this just passes an Error-shaped dictionary to JavaScript, but we would like to automatically generate real JavaScript Error objects in the future.

    Promises #

    Native modules can also fulfill a promise, which can simplify your code, especially when using ES2016's async/await syntax. When the last parameters of a bridged native method are an RCTPromiseResolveBlock and RCTPromiseRejectBlock, its corresponding JS method will return a JS Promise object.

    Refactoring the above code to use a promise instead of callbacks looks like this:

    RCT_REMAP_METHOD(findEvents, resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) { @@ -49,7 +50,8 @@ CalendarManager.if (events) { resolve(events); } else { - reject(error); + NSError *error = ... + reject(@"no_events", @"There were no events", error); } }

    The JavaScript counterpart of this method returns a Promise. This means you can use the await keyword within an async function to call it and wait for its result:

    async function updateEvents() { try { @@ -61,7 +63,7 @@ CalendarManager.} } -updateEvents();

    Threading #

    The native module should not have any assumptions about what thread it is being called on. React Native invokes native modules methods on a separate serial GCD queue, but this is an implementation detail and might change. The - (dispatch_queue_t)methodQueue method allows the native module to specify which queue its methods should be run on. For example, if it needs to use a main-thread-only iOS API, it should specify this via:

    - (dispatch_queue_t)methodQueue +updateEvents();

    Threading #

    The native module should not have any assumptions about what thread it is being called on. React Native invokes native modules methods on a separate serial GCD queue, but this is an implementation detail and might change. The - (dispatch_queue_t)methodQueue method allows the native module to specify which queue its methods should be run on. For example, if it needs to use a main-thread-only iOS API, it should specify this via:

    - (dispatch_queue_t)methodQueue { return dispatch_get_main_queue(); }

    Similarly, if an operation may take a long time to complete, the native module should not block and can specify it's own queue to run operations on. For example, the RCTAsyncLocalStorage module creates it's own queue so the React queue isn't blocked waiting on potentially slow disk access:

    - (dispatch_queue_t)methodQueue @@ -75,10 +77,10 @@ CalendarManager. // You can invoke callback from any thread/queue callback(@[...]); }); -}

    NOTE: Sharing dispatch queues between modules

    The methodQueue method will be called once when the module is initialized, and then retained by the bridge, so there is no need to retain the queue yourself, unless you wish to make use of it within your module. However, if you wish to share the same queue between multiple modules then you will need to ensure that you retain and return the same queue instance for each of them; merely returning a queue of the same name for each won't work.

    Exporting Constants #

    A native module can export constants that are immediately available to JavaScript at runtime. This is useful for communicating static data that would otherwise require a round-trip through the bridge.

    - (NSDictionary *)constantsToExport +}

    NOTE: Sharing dispatch queues between modules

    The methodQueue method will be called once when the module is initialized, and then retained by the bridge, so there is no need to retain the queue yourself, unless you wish to make use of it within your module. However, if you wish to share the same queue between multiple modules then you will need to ensure that you retain and return the same queue instance for each of them; merely returning a queue of the same name for each won't work.

    Exporting Constants #

    A native module can export constants that are immediately available to JavaScript at runtime. This is useful for communicating static data that would otherwise require a round-trip through the bridge.

    - (NSDictionary *)constantsToExport { return @{ @"firstDayOfTheWeek": @"Monday" }; -}

    JavaScript can use this value right away, synchronously:

    console.log(CalendarManager.firstDayOfTheWeek);

    Note that the constants are exported only at initialization time, so if you change constantsToExport values at runtime it won't affect the JavaScript environment.

    Enum Constants #

    Enums that are defined via NS_ENUM cannot be used as method arguments without first extending RCTConvert.

    In order to export the following NS_ENUM definition:

    typedef NS_ENUM(NSInteger, UIStatusBarAnimation) { +}

    JavaScript can use this value right away, synchronously:

    console.log(CalendarManager.firstDayOfTheWeek);

    Note that the constants are exported only at initialization time, so if you change constantsToExport values at runtime it won't affect the JavaScript environment.

    Enum Constants #

    Enums that are defined via NS_ENUM cannot be used as method arguments without first extending RCTConvert.

    In order to export the following NS_ENUM definition:

    typedef NS_ENUM(NSInteger, UIStatusBarAnimation) { UIStatusBarAnimationNone, UIStatusBarAnimationFade, UIStatusBarAnimationSlide, @@ -95,7 +97,7 @@ CalendarManager.}; RCT_EXPORT_METHOD(updateStatusBarAnimation:(UIStatusBarAnimation)animation - completion:(RCTResponseSenderBlock)callback)

    Your enum will then be automatically unwrapped using the selector provided (integerValue in the above example) before being passed to your exported method.

    Sending Events to JavaScript #

    The native module can signal events to JavaScript without being invoked directly. The easiest way to do this is to use eventDispatcher:

    #import "RCTBridge.h" + completion:(RCTResponseSenderBlock)callback)

    Your enum will then be automatically unwrapped using the selector provided (integerValue in the above example) before being passed to your exported method.

    Sending Events to JavaScript #

    The native module can signal events to JavaScript without being invoked directly. The easiest way to do this is to use eventDispatcher:

    #import "RCTBridge.h" #import "RCTEventDispatcher.h" @implementation CalendarManager @@ -109,7 +111,7 @@ CalendarManager.:@{@"name": eventName}]; } -@end

    JavaScript code can subscribe to these events:

    var { NativeAppEventEmitter } = require('react-native'); +@end

    JavaScript code can subscribe to these events:

    import { NativeAppEventEmitter } from 'react-native'; var subscription = NativeAppEventEmitter.addListener( 'EventReminder', @@ -117,7 +119,7 @@ CalendarManager.); ... // Don't forget to unsubscribe, typically in componentWillUnmount -subscription.remove();

    For more examples of sending events to JavaScript, see RCTLocationObserver.

    Exporting Swift #

    Swift doesn't have support for macros so exposing it to React Native requires a bit more setup but works relatively the same.

    Let's say we have the same CalendarManager but as a Swift class:

    // CalendarManager.swift +subscription.remove();

    For more examples of sending events to JavaScript, see RCTLocationObserver.

    Exporting Swift #

    Swift doesn't have support for macros so exposing it to React Native requires a bit more setup but works relatively the same.

    Let's say we have the same CalendarManager but as a Swift class:

    // CalendarManager.swift @objc(CalendarManager) class CalendarManager: NSObject { @@ -134,7 +136,7 @@ class CalendarManagerRCT_EXTERN_METHOD(addEvent:(NSString *)name location:(NSString *)location date:(nonnull NSNumber *)date) @end

    For those of you new to Swift and Objective-C, whenever you mix the two languages in an iOS project, you will also need an additional bridging file, known as a bridging header, to expose the Objective-C files to Swift. Xcode will offer to create this header file for you if you add your Swift file to your app through the Xcode File>New File menu option. You will need to import RCTBridgeModule.h in this header file.

    // CalendarManager-Bridging-Header.h -#import "RCTBridgeModule.h"

    You can also use RCT_EXTERN_REMAP_MODULE and RCT_EXTERN_REMAP_METHOD to alter the JavaScript name of the module or methods you are exporting. For more information see RCTBridgeModule.

    © 2015 Facebook Inc.

    NativeMethodsMixin #

    Edit on GitHub

    NativeMethodsMixin provides methods to access the underlying native +NativeMethodsMixin – React Native | A framework for building native apps using React

    NativeMethodsMixin #

    Edit on GitHub

    NativeMethodsMixin provides methods to access the underlying native component directly. This can be useful in cases when you want to focus a view or measure its on-screen dimensions, for example.

    The methods described here are available on most of the default components provided by React Native. Note, however, that they are not available on composite components that aren't directly backed by a native view. This will generally include most components that you define in your own app. For more information, see Direct -Manipulation.

    Methods #

    static measure(callback: MeasureOnSuccessCallback) #

    Determines the location on screen, width, and height of the given view and +Manipulation.

    Methods #

    static measure(callback: MeasureOnSuccessCallback) #

    Determines the location on screen, width, and height of the given view and returns the values via an async callback. If successful, the callback will be called with the following arguments:

    • x
    • y
    • width
    • height
    • pageX
    • pageY

    Note that these measurements are not available until after the rendering has been completed in native. If you need the measurements as soon as possible, consider using the onLayout -prop instead.

    static measureLayout(relativeToNativeNode: number, onSuccess: MeasureLayoutOnSuccessCallback, onFail: () => void) #

    Like measure(), but measures the view relative an ancestor, +prop instead.

    static measureLayout(relativeToNativeNode: number, onSuccess: MeasureLayoutOnSuccessCallback, onFail: () => void) #

    Like measure(), but measures the view relative an ancestor, specified as relativeToNativeNode. This means that the returned x, y are relative to the origin x, y of the ancestor view.

    As always, to obtain a native node handle for a component, you can use -React.findNodeHandle(component).

    static setNativeProps(nativeProps: Object) #

    This function sends props straight to native. They will not participate in +React.findNodeHandle(component).

    static setNativeProps(nativeProps: Object) #

    This function sends props straight to native. They will not participate in future diff process - this means that if you do not include them in the next render, they will remain active (see Direct -Manipulation).

    static focus() #

    Requests focus for the given input or view. The exact behavior triggered -will depend on the platform and type of view.

    static blur() #

    Removes focus from an input or view. This is the opposite of focus().

    © 2015 Facebook Inc.

    Navigator Comparison #

    Edit on GitHub

    The differences between Navigator +Navigator Comparison – React Native | A framework for building native apps using React

    Navigator Comparison #

    Edit on GitHub

    The differences between Navigator and NavigatorIOS are a common source of confusion for newcomers.

    Both Navigator and NavigatorIOS are components that allow you to manage the navigation in your app between various "scenes" (another word @@ -12,7 +12,7 @@ class, and Navigator re-implements that functionality entirely in JavaScript as a React component. A corollary of this is that Navigator will be compatible with Android and iOS, whereas NavigatorIOS will only work on the one platform. Below is an itemized list of differences -between the two.

    Navigator #

    • Extensive API makes it completely customizable from JavaScript.
    • Under active development from the React Native team.
    • Written in JavaScript.
    • Works on iOS and Android.
    • Includes a simple navigation bar component similar to the default NavigatorIOS bar: Navigator.NavigationBar, and another with breadcrumbs called Navigator.BreadcrumbNavigationBar. See the UIExplorer demo to try them out and see how to use them.
      • Currently animations are good and improving, but they are still less refined than Apple's, which you get from NavigatorIOS.
    • You can provide your own navigation bar by passing it through the navigationBar prop.

    NavigatorIOS #

    • Small, limited API makes it much less customizable than Navigator in its current form.
    • Development belongs to open-source community - not used by the React Native team on their apps.
      • A result of this is that there is currently a backlog of unresolved bugs, nobody who uses this has stepped up to take ownership for it yet.
    • Wraps UIKit, so it works exactly the same as it would on another native app. Lives in Objective-C and JavaScript.
      • Consequently, you get the animations and behavior that Apple has developed.
    • iOS only.
    • Includes a navigation bar by default; this navigation bar is not a React Native view component and the style can only be slightly modified.

    For most non-trivial apps, you will want to use Navigator - it won't be long before you run into issues when trying to do anything complex with NavigatorIOS.

    © 2015 Facebook Inc.

    Navigator #

    Edit on GitHub

    Use Navigator to transition between different scenes in your app. To +Navigator – React Native | A framework for building native apps using React

    Navigator #

    Edit on GitHub

    Use Navigator to transition between different scenes in your app. To accomplish this, provide route objects to the navigator to identify each scene, and also a renderScene function that the navigator can use to render the scene for a given route.

    To change the animation or gesture properties of the scene, provide a configureScene prop to get the config object for a given route. See Navigator.SceneConfigs for default animations and more info on -scene config options.

    Basic Usage #

    <Navigator +scene config options.

    Basic Usage #

    <Navigator initialRoute={{name: 'My First Scene', index: 0}} renderScene={(route, navigator) => <MySceneComponent @@ -23,23 +23,23 @@ scene config options.

    Basic Usag }} /> } - />

    Navigator Methods #

    If you have a ref to the Navigator element, you can invoke several methods + />

    Navigator Methods #

    If you have a ref to the Navigator element, you can invoke several methods on it to trigger navigation:

    • getCurrentRoutes() - returns the current list of routes
    • jumpBack() - Jump backward without unmounting the current scene
    • jumpForward() - Jump forward to the next scene in the route stack
    • jumpTo(route) - Transition to an existing scene without unmounting
    • push(route) - Navigate forward to a new scene, squashing any scenes that you could jumpForward to
    • pop() - Transition back and unmount the current scene
    • replace(route) - Replace the current scene with a new route
    • replaceAtIndex(route, index) - Replace a scene as specified by an index
    • replacePrevious(route) - Replace the previous scene
    • resetTo(route) - Navigate to a new scene and reset route stack
    • immediatelyResetRouteStack(routeStack) - Reset every scene with an array of routes
    • popToRoute(route) - Pop to a particular scene, as specified by its route. All scenes after it will be unmounted
    • popToTop() - Pop to the first scene in the stack, unmounting every - other scene

    Props #

    configureScene function #

    Optional function that allows configuration about scene animations and + other scene

    Props #

    configureScene function #

    Optional function that allows configuration about scene animations and gestures. Will be invoked with the route and the routeStack and should -return a scene configuration object

    (route, routeStack) => Navigator.SceneConfigs.FloatFromRight

    initialRoute object #

    Specify a route to start on. A route is an object that the navigator +return a scene configuration object

    (route, routeStack) => Navigator.SceneConfigs.FloatFromRight

    initialRoute object #

    Specify a route to start on. A route is an object that the navigator will use to identify each scene to render. initialRoute must be a route in the initialRouteStack if both props are provided. The -initialRoute will default to the last item in the initialRouteStack.

    initialRouteStack [object] #

    Provide a set of routes to initially mount. Required if no initialRoute +initialRoute will default to the last item in the initialRouteStack.

    initialRouteStack [object] #

    Provide a set of routes to initially mount. Required if no initialRoute is provided. Otherwise, it will default to an array containing only the -initialRoute

    navigationBar node #

    Optionally provide a navigation bar that persists across scene -transitions

    navigator object #

    Optionally provide the navigator object from a parent Navigator

    onDidFocus function #

    Deprecated

    Use navigationContext.addListener('didfocus', callback) instead.

    Will be called with the new route of each scene after the transition is -complete or after the initial mounting

    onWillFocus function #

    Deprecated

    Use navigationContext.addListener('willfocus', callback) instead.

    Will emit the target route upon mounting and before each nav transition

    renderScene function #

    Required function which renders the scene for a given route. Will be +initialRoute

    navigationBar node #

    Optionally provide a navigation bar that persists across scene +transitions

    navigator object #

    Optionally provide the navigator object from a parent Navigator

    onDidFocus function #

    Will be called with the new route of each scene after the transition is +complete or after the initial mounting

    onWillFocus function #

    Will emit the target route upon mounting and before each nav transition

    renderScene function #

    Required function which renders the scene for a given route. Will be invoked with the route and the navigator object

    (route, navigator) => - <MySceneComponent title={route.title} navigator={navigator} />

    sceneStyle View#style #

    Styles to apply to the container of each scene

    © 2015 Facebook Inc.

    NavigatorIOS #

    Edit on GitHub

    NavigatorIOS wraps UIKit navigation and allows you to add back-swipe +NavigatorIOS – React Native | A framework for building native apps using React

    NavigatorIOS #

    Edit on GitHub

    NavigatorIOS wraps UIKit navigation and allows you to add back-swipe functionality across your app.

    NOTE: This Component is not maintained by Facebook

    This component is under community responsibility. If a pure JavaScript solution fits your needs you may try the Navigator -component instead.

    Routes #

    A route is an object used to describe each page in the navigator. The first +component instead.

    Routes #

    A route is an object used to describe each page in the navigator. The first route is provided to NavigatorIOS as initialRoute:

    render: function() { return ( <NavigatorIOS @@ -14,7 +14,7 @@ route is provided to NavigatorIOS as initialRoute:

    ); },

    Now MyView will be rendered by the navigator. It will receive the route object in the route prop, a navigator, and all of the props specified in -passProps.

    See the initialRoute propType for a complete definition of a route.

    Navigator #

    A navigator is an object of navigation functions that a view can call. It +passProps.

    See the initialRoute propType for a complete definition of a route.

    Navigator #

    A navigator is an object of navigation functions that a view can call. It is passed as a prop to any component rendered by NavigatorIOS.

    var MyView = React.createClass({ _handleBackButtonPress: function() { this.props.navigator.pop(); @@ -38,10 +38,10 @@ transitions back to it
  • resetTo(route) - Replaces the top it });
  • Props passed to the NavigatorIOS component will set the default configuration for the navigation bar. Props passed as properties to a route object will set the configuration for that route's navigation bar, overriding any props -passed to the NavigatorIOS component.

    Props #

    barTintColor string #

    The default background color of the navigation bar

    initialRoute {component: function, title: string, passProps: object, backButtonIcon: Image.propTypes.source, backButtonTitle: string, leftButtonIcon: Image.propTypes.source, leftButtonTitle: string, onLeftButtonPress: function, rightButtonIcon: Image.propTypes.source, rightButtonTitle: string, onRightButtonPress: function, wrapperStyle: [object Object], navigationBarHidden: bool, shadowHidden: bool, tintColor: string, barTintColor: string, titleTextColor: string, translucent: bool} #

    NavigatorIOS uses "route" objects to identify child views, their props, +passed to the NavigatorIOS component.

    Props #

    barTintColor string #

    The default background color of the navigation bar

    initialRoute {component: function, title: string, passProps: object, backButtonIcon: Image.propTypes.source, backButtonTitle: string, leftButtonIcon: Image.propTypes.source, leftButtonTitle: string, onLeftButtonPress: function, rightButtonIcon: Image.propTypes.source, rightButtonTitle: string, onRightButtonPress: function, wrapperStyle: [object Object], navigationBarHidden: bool, shadowHidden: bool, tintColor: string, barTintColor: string, titleTextColor: string, translucent: bool} #

    NavigatorIOS uses "route" objects to identify child views, their props, and navigation bar configuration. "push" and all the other navigation -operations expect routes to be like this:

    itemWrapperStyle View#style #

    The default wrapper style for components in the navigator. -A common use case is to set the backgroundColor for every page

    navigationBarHidden bool #

    A Boolean value that indicates whether the navigation bar is hidden by default

    shadowHidden bool #

    A Boolean value that indicates whether to hide the 1px hairline shadow by default

    tintColor string #

    The default color used for buttons in the navigation bar

    titleTextColor string #

    The default text color of the navigation bar title

    translucent bool #

    A Boolean value that indicates whether the navigation bar is translucent by default

    Examples #

    Edit on GitHub
    'use strict'; +operations expect routes to be like this:

    itemWrapperStyle View#style #

    The default wrapper style for components in the navigator. +A common use case is to set the backgroundColor for every page

    navigationBarHidden bool #

    A Boolean value that indicates whether the navigation bar is hidden by default

    shadowHidden bool #

    A Boolean value that indicates whether to hide the 1px hairline shadow by default

    tintColor string #

    The default color used for buttons in the navigation bar

    titleTextColor string #

    The default text color of the navigation bar title

    translucent bool #

    A Boolean value that indicates whether the navigation bar is translucent by default

    Examples #

    Edit on GitHub
    'use strict'; var React = require('react-native'); var ViewExample = require('./ViewExample'); @@ -276,7 +276,7 @@ A common use case is to set the backgroundColor for every page

    }, }); -module.exports = NavigatorIOSExample;
    © 2015 Facebook Inc.

    NetInfo #

    Edit on GitHub

    NetInfo exposes info about online/offline status

    NetInfo.fetch().done((reach) => { +NetInfo – React Native | A framework for building native apps using React

    NetInfo #

    Edit on GitHub

    NetInfo exposes info about online/offline status

    NetInfo.fetch().done((reach) => { console.log('Initial: ' + reach); }); function handleFirstConnectivityChange(reach) { @@ -11,13 +11,13 @@ NetInfo.addEventListener( 'change', handleFirstConnectivityChange -);

    IOS #

    Asynchronously determine if the device is online and on a cellular network.

    • none - device is offline
    • wifi - device is online and connected via wifi, or is the iOS simulator
    • cell - device is connected via Edge, 3G, WiMax, or LTE
    • unknown - error case and the network status is unknown

    Android #

    To request network info, you need to add the following line to your +);

    IOS #

    Asynchronously determine if the device is online and on a cellular network.

    • none - device is offline
    • wifi - device is online and connected via wifi, or is the iOS simulator
    • cell - device is connected via Edge, 3G, WiMax, or LTE
    • unknown - error case and the network status is unknown

    Android #

    To request network info, you need to add the following line to your app's AndroidManifest.xml:

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> -Asynchronously determine if the device is connected and details about that connection.

    Android Connectivity Types.

    • NONE - device is offline
    • BLUETOOTH - The Bluetooth data connection.
    • DUMMY - Dummy data connection.
    • ETHERNET - The Ethernet data connection.
    • MOBILE - The Mobile data connection.
    • MOBILE_DUN - A DUN-specific Mobile data connection.
    • MOBILE_HIPRI - A High Priority Mobile data connection.
    • MOBILE_MMS - An MMS-specific Mobile data connection.
    • MOBILE_SUPL - A SUPL-specific Mobile data connection.
    • VPN - A virtual network using one or more native bearers. Requires API Level 21
    • WIFI - The WIFI data connection.
    • WIMAX - The WiMAX data connection.
    • UNKNOWN - Unknown data connection.

    The rest ConnectivityStates are hidden by the Android API, but can be used if necessary.

    isConnectionExpensive #

    Available on Android. Detect if the current active connection is metered or not. A network is +Asynchronously determine if the device is connected and details about that connection.

    Android Connectivity Types.

    • NONE - device is offline
    • BLUETOOTH - The Bluetooth data connection.
    • DUMMY - Dummy data connection.
    • ETHERNET - The Ethernet data connection.
    • MOBILE - The Mobile data connection.
    • MOBILE_DUN - A DUN-specific Mobile data connection.
    • MOBILE_HIPRI - A High Priority Mobile data connection.
    • MOBILE_MMS - An MMS-specific Mobile data connection.
    • MOBILE_SUPL - A SUPL-specific Mobile data connection.
    • VPN - A virtual network using one or more native bearers. Requires API Level 21
    • WIFI - The WIFI data connection.
    • WIMAX - The WiMAX data connection.
    • UNKNOWN - Unknown data connection.

    The rest ConnectivityStates are hidden by the Android API, but can be used if necessary.

    isConnectionExpensive #

    Available on Android. Detect if the current active connection is metered or not. A network is classified as metered when the user is sensitive to heavy data usage on that connection due to monetary costs, data limitations or battery/performance issues.

    NetInfo.isConnectionExpensive((isConnectionExpensive) => { console.log('Connection is ' + (isConnectionExpensive ? 'Expensive' : 'Not Expensive')); -});

    isConnected #

    Available on all platforms. Asynchronously fetch a boolean to determine +});

    isConnected #

    Available on all platforms. Asynchronously fetch a boolean to determine internet connectivity.

    NetInfo.isConnected.fetch().done((isConnected) => { console.log('First, is ' + (isConnected ? 'online' : 'offline')); }); @@ -31,7 +31,7 @@ internet connectivity.

    NetInfo.isConnected.addEventListener( 'change', handleFirstConnectivityChange -);

    Methods #

    static addEventListener(eventName: ChangeEventName, handler: Function) #

    static removeEventListener(eventName: ChangeEventName, handler: Function) #

    static fetch() #

    static isConnectionExpensive(callback: (metered: ?boolean, error?: string) => void) #

    Properties #

    isConnected: ObjectExpression #

    Examples #

    Edit on GitHub
    'use strict'; +);

    Methods #

    static addEventListener(eventName: ChangeEventName, handler: Function) #

    static removeEventListener(eventName: ChangeEventName, handler: Function) #

    static fetch() #

    static isConnectionExpensive(callback: (metered: ?boolean, error?: string) => void) #

    Properties #

    isConnected: ObjectExpression #

    Examples #

    Edit on GitHub
    'use strict'; const React = require('react-native'); const { @@ -197,7 +197,7 @@ exports.examples : 'Asynchronously check isConnectionExpensive', render(): ReactElement { return <IsConnectionExpensive />; } }, -];
    © 2015 Facebook Inc.

    Network #

    Edit on GitHub

    One of React Native's goals is to be a playground where we can experiment with different architectures and crazy ideas. Since browsers are not flexible enough, we had no choice but to reimplement the entire stack. In the places that we did not intend to change anything, we tried to be as faithful as possible to the browser APIs. The networking stack is a great example.

    Fetch #

    fetch is a better networking API being worked on by the standards committee and is already available in Chrome. It is available in React Native by default.

    Usage #

    fetch('https://mywebsite.com/endpoint/')

    Include a request object as the optional second argument to customize the HTTP request:

    fetch('https://mywebsite.com/endpoint/', { +Network – React Native | A framework for building native apps using React

    Network #

    Edit on GitHub

    One of React Native's goals is to be a playground where we can experiment with different architectures and crazy ideas. Since browsers are not flexible enough, we had no choice but to reimplement the entire stack. In the places that we did not intend to change anything, we tried to be as faithful as possible to the browser APIs. The networking stack is a great example.

    Fetch #

    fetch is a better networking API being worked on by the standards committee and is already available in Chrome. It is available in React Native by default.

    Usage #

    fetch('https://mywebsite.com/endpoint/')

    Include a request object as the optional second argument to customize the HTTP request:

    fetch('https://mywebsite.com/endpoint/', { method: 'POST', headers: { 'Accept': 'application/json', @@ -8,21 +8,27 @@ firstParam: 'yourValue', secondParam: 'yourOtherValue', }) -})

    Async #

    fetch returns a Promise that can be processed in two ways:

    1. Using then and catch in synchronous code:
    fetch('https://mywebsite.com/endpoint.php') - .then((response) => response.text()) - .then((responseText) => { - console.log(responseText); - }) - .catch((error) => { - console.warn(error); - });
    1. Called within an asynchronous function using ES7 async/await syntax:
    async getUsersFromApi() { +})

    Async #

    fetch returns a Promise that can be processed in two ways:

    1. Using then and catch in synchronous code:

      fetch('https://mywebsite.com/endpoint.php') +.then((response) => response.text()) +.then((responseText) => { + console.log(responseText); +}) +.catch((error) => { + console.warn(error); +});
    2. Called within an asynchronous function using ES7 async/await syntax:

      class MyComponent extends React.Component { +... +async getUsersFromApi() { try { let response = await fetch('https://mywebsite.com/endpoint/'); - return response.users; + let responseJson = await response.json(); + return responseJson.users; } catch(error) { - throw error; + // Handle error + console.error(error); } -}
      • Note: Errors thrown by rejected Promises need to be caught, or they will be swallowed silently

      WebSocket #

      WebSocket is a protocol providing full-duplex communication channels over a single TCP connection.

      var ws = new WebSocket('ws://host.com/path'); +} +... +}
    3. Note: Errors thrown by rejected Promises need to be caught, or they will be swallowed silently

    WebSocket #

    WebSocket is a protocol providing full-duplex communication channels over a single TCP connection.

    var ws = new WebSocket('ws://host.com/path'); ws.onopen = () => { // connection opened @@ -42,7 +48,7 @@ ws.onerror = ws.onclose = (e) => { // connection closed console.log(e.code, e.reason); -};

    XMLHttpRequest #

    XMLHttpRequest API is implemented on-top of iOS networking apis. The notable difference from web is the security model: you can read from arbitrary websites on the internet since there is no concept of CORS.

    var request = new XMLHttpRequest(); +};

    XMLHttpRequest #

    XMLHttpRequest API is implemented on-top of iOS networking apis. The notable difference from web is the security model: you can read from arbitrary websites on the internet since there is no concept of CORS.

    var request = new XMLHttpRequest(); request.onreadystatechange = (e) => { if (request.readyState !== 4) { return; @@ -56,7 +62,7 @@ request.onreadystatechange }; request.open('GET', 'https://mywebsite.com/endpoint.php'); -request.send();

    Please follow the MDN Documentation for a complete description of the API.

    As a developer, you're probably not going to use XMLHttpRequest directly as its API is very tedious to work with. But the fact that it is implemented and compatible with the browser API gives you the ability to use third-party libraries such as Parse, frisbee, or axios directly from npm.

    © 2015 Facebook Inc.

    PanResponder #

    Edit on GitHub

    PanResponder reconciles several touches into a single gesture. It makes +PanResponder – React Native | A framework for building native apps using React

    PanResponder #

    Edit on GitHub

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

    It provides a predictable wrapper of the responder handlers provided by the gesture responder system. For each handler, it provides a new gestureState object alongside the native event object:

    onPanResponderMove: (event, gestureState) => {}

    A native event 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

    A gestureState object has the following:

    • stateID - ID of the gestureState- persisted as long as there at least - one touch on screen
    • moveX - the latest screen coordinates of the recently-moved touch
    • moveY - the latest screen coordinates of the recently-moved touch
    • x0 - the screen coordinates of the responder grant
    • y0 - the screen coordinates of the responder grant
    • dx - accumulated distance of the gesture since the touch started
    • dy - accumulated distance of the gesture since the touch started
    • vx - current velocity of the gesture
    • vy - current velocity of the gesture
    • numberActiveTouches - Number of touches currently on screen

    Basic Usage #

    componentWillMount: function() { + one touch on screen
  • moveX - the latest screen coordinates of the recently-moved touch
  • moveY - the latest screen coordinates of the recently-moved touch
  • x0 - the screen coordinates of the responder grant
  • y0 - the screen coordinates of the responder grant
  • dx - accumulated distance of the gesture since the touch started
  • dy - accumulated distance of the gesture since the touch started
  • vx - current velocity of the gesture
  • vy - current velocity of the gesture
  • numberActiveTouches - Number of touches currently on screen
  • Basic Usage #

    componentWillMount: function() { this._panResponder = PanResponder.create({ // Ask to be the responder: onStartShouldSetPanResponder: (evt, gestureState) => true, @@ -45,8 +45,8 @@ native event object:

    onPanResponderMov return ( <View {...this._panResponder.panHandlers} /> ); - },

    Working Example #

    To see it in action, try the -PanResponder example in UIExplorer

    Methods #

    static create(config: object) #

    @param {object} config Enhanced versions of all of the responder callbacks + },

    Working Example #

    To see it in action, try the +PanResponder example in UIExplorer

    Methods #

    static create(config: object) #

    @param {object} config Enhanced versions of all of the responder callbacks that provide not only the typical ResponderSyntheticEvent, but also the PanResponder gesture state. Simply replace the word Responder with PanResponder in each of the typical onResponder* callbacks. For @@ -57,7 +57,7 @@ as well.

    Be careful with onStartShould* callbacks. They only reflect updat Once the node is the responder, you can rely on every start/end event being processed by the gesture and gestureState being updated accordingly. (numberActiveTouches) may not be totally accurate unless you -are the responder.

    Examples #

    Edit on GitHub
    'use strict'; +are the responder.

    Examples #

    Edit on GitHub
    'use strict'; var React = require('react-native'); var { @@ -185,7 +185,7 @@ are the responder.

    },}); -module.exports = PanResponderExample;
    © 2015 Facebook Inc.

    Performance #

    Edit on GitHub

    A compelling reason for using React Native instead of WebView-based +Performance – React Native | A framework for building native apps using React

    Performance #

    Edit on GitHub

    A compelling reason for using React Native instead of WebView-based tools is to achieve 60 FPS and a native look & feel to your apps. Where possible, we would like for React Native to do the right thing and help you to focus on your app instead of performance optimization, but there @@ -7,7 +7,7 @@ are areas where we're not quite there yet, and others where React Native best way to optimize for you and so manual intervention will be necessary.

    This guide is intended to teach you some basics to help you to troubleshoot performance issues, as well as discuss common sources of -problems and their suggested solutions.

    What you need to know about frames #

    Your grandparents' generation called movies "moving +problems and their suggested solutions.

    What you need to know about frames #

    Your grandparents' generation called movies "moving pictures" for a reason: realistic motion in video is an illusion created by quickly changing static images at a consistent speed. We refer to each of these images as @@ -20,7 +20,7 @@ for that interval. If you are unable to do the work necessary to generate that frame within the allotted 16.67ms, then you will "drop a frame" and the UI will appear unresponsive.

    Now to confuse the matter a little bit, open up the developer menu in your app and toggle Show FPS Monitor. You will notice that there are -two different frame rates.

    JavaScript frame rate #

    For most React Native applications, your business logic will run on the +two different frame rates.

    JavaScript frame rate #

    For most React Native applications, your business logic will run on the JavaScript thread. This is where your React application lives, API calls are made, touch events are processed, etc... Updates to native-backed views are batched and sent over to the native side at the end of each iteration of the event loop, before the frame deadline (if @@ -38,7 +38,7 @@ controlled by the JavaScript thread. Sometimes components will do additional work on componentDidMount, which might result in a second stutter in the transition.

    Another example is responding to touches: if you are doing work across multiple frames on the JavaScript thread, you might notice a delay in -responding to TouchableOpacity, for example. This is because the JavaScript thread is busy and cannot process the raw touch events sent over from the main thread. As a result, TouchableOpacity cannot react to the touch events and command the native view to adjust its opacity.

    Main thread (aka UI thread) frame rate #

    Many people have noticed that performance of NavigatorIOS is better +responding to TouchableOpacity, for example. This is because the JavaScript thread is busy and cannot process the raw touch events sent over from the main thread. As a result, TouchableOpacity cannot react to the touch events and command the native view to adjust its opacity.

    Main thread (aka UI thread) frame rate #

    Many people have noticed that performance of NavigatorIOS is better out of the box than Navigator. The reason for this is that the animations for the transitions are done entirely on the main thread, and so they are not interrupted by frame drops on the JavaScript thread. @@ -46,10 +46,10 @@ so they are not interrupted by frame drops on the JavaScript thread. anyways.)

    Similarly, you can happily scroll up and down through a ScrollView when the JavaScript thread is locked up because the ScrollView lives on the main thread (the scroll events are dispatched to the JS thread though, -but their receipt is not necessary for the scroll to occur).

    Common sources of performance problems #

    Development mode (dev=true) #

    JavaScript thread performance suffers greatly when running in dev mode. +but their receipt is not necessary for the scroll to occur).

    Common sources of performance problems #

    Development mode (dev=true) #

    JavaScript thread performance suffers greatly when running in dev mode. This is unavoidable: a lot more work needs to be done at runtime to provide you with good warnings and error messages, such as validating -propTypes and various other assertions.

    Slow navigator transitions #

    As mentioned above, Navigator animations are controlled by the +propTypes and various other assertions.

    Slow navigator transitions #

    As mentioned above, Navigator animations are controlled by the JavaScript thread. Imagine the "push from right" scene transition: each frame, the new scene is moved from the right to left, starting offscreen (let's say at an x-offset of 320) and ultimately settling when the scene sits @@ -109,35 +109,35 @@ load the Facebook app you see a placeholder news feed item with grey rectangles where text will be. If you are rendering a Map in your new scene, you might want to display a grey placeholder view or a spinner until the transition is complete as this can actually cause frames to be -dropped on the main thread.

    ListView initial rendering is too slow or scroll performance is bad for large lists #

    This is an issue that comes up frequently because iOS ships with +dropped on the main thread.

    ListView initial rendering is too slow or scroll performance is bad for large lists #

    This is an issue that comes up frequently because iOS ships with UITableView which gives you very good performance by re-using underlying UIViews. Work is in progress to do something similar with React Native, but until then we have some tools at our disposal to help us tweak the performance to suit our needs. It may not be possible to get all the way there, but a little bit of creativity and experimentation with these -options can go a long way.

    initialListSize #

    This prop specifies how many rows we want to render on our first render +options can go a long way.

    initialListSize #

    This prop specifies how many rows we want to render on our first render pass. If we are concerned with getting something on screen as quickly as possible, we could set the initialListSize to 1, and we'll quickly see other rows fill in on subsequent frames. The number of rows per -frame is determined by the pageSize.

    pageSize #

    After the initial render where initialListSize is used, ListView looks +frame is determined by the pageSize.

    pageSize #

    After the initial render where initialListSize is used, ListView looks at the pageSize to determine how many rows to render per frame. The default here is 1 -- but if your views are very small and inexpensive to render, you might want to bump this up. Tweak it and find what works for -your use case.

    scrollRenderAheadDistance #

    "How early to start rendering rows before they come on screen, in pixels."

    If we had a list with 2000 items and rendered them all immediately that +your use case.

    scrollRenderAheadDistance #

    "How early to start rendering rows before they come on screen, in pixels."

    If we had a list with 2000 items and rendered them all immediately that would be a poor use of both memory and computational resources. It would also probably cause some pretty awful jank. So the scrollRenderAhead distance allows us to specify for far beyond the current viewport we -should continue to render rows.

    removeClippedSubviews #

    "When true, offscreen child views (whose overflow value is hidden) +should continue to render rows.

    removeClippedSubviews #

    "When true, offscreen child views (whose overflow value is hidden) are removed from their native backing superview when offscreen. This can improve scrolling performance on long lists. The default value is true."(The default value is false before version 0.14-rc).

    This is an extremely important optimization to apply on large ListViews. On Android the overflow value is always hidden so you don't need to worry about setting it, but on iOS you need to be sure to set overflow: -hidden on row containers.

    My component renders too slowly and I don't need it all immediately #

    It's common at first to overlook ListView, but using it properly is +hidden on row containers.

    My component renders too slowly and I don't need it all immediately #

    It's common at first to overlook ListView, but using it properly is often key to achieving solid performance. As discussed above, it provides you with a set of tools that lets you split rendering of your view across various frames and tweak that behavior to fit your specific -needs. Remember that ListView can be horizontal too.

    JS FPS plunges when re-rendering a view that hardly changes #

    If you are using a ListView, you must provide a rowHasChanged function +needs. Remember that ListView can be horizontal too.

    JS FPS plunges when re-rendering a view that hardly changes #

    If you are using a ListView, you must provide a rowHasChanged function that can reduce a lot of work by quickly determining whether or not a row needs to be re-rendered. If you are using immutable data structures, this would be as simple as a reference equality check.

    Similarly, you can implement shouldComponentUpdate and indicate the @@ -148,7 +148,7 @@ PureRenderMixin to do this for you. Once again, immutable data structures are useful to keep this fast -- if you have to do a deep comparison of a large list of objects, it may be that re-rendering your entire component would be quicker, and it would certainly require less -code.

    Dropping JS thread FPS because of doing a lot of work on the JavaScript thread at the same time #

    "Slow Navigator transitions" is the most common manifestation of this, +code.

    Dropping JS thread FPS because of doing a lot of work on the JavaScript thread at the same time #

    "Slow Navigator transitions" is the most common manifestation of this, but there are other times this can happen. Using InteractionManager can be a good approach, but if the user experience cost is too high to delay work during an animation, then you might want to consider @@ -163,16 +163,16 @@ information about how to use LayoutAnimation.

    Caveats: - LayoutAnimation only exists on iOS. - LayoutAnimation only works for fire-and-forget animations ("static" animations) -- if it must be be interruptible, you will need to use -Animated.

    Moving a view on the screen (scrolling, translating, rotating) drops UI thread FPS #

    This is especially true when you have text with a transparent background +Animated.

    Moving a view on the screen (scrolling, translating, rotating) drops UI thread FPS #

    This is especially true when you have text with a transparent background positioned on top of an image, or any other situation where alpha compositing would be required to re-draw the view on each frame. You will find that enabling shouldRasterizeIOS or renderToHardwareTextureAndroid can help with this significantly.

    Be careful not to overuse this or your memory usage could go through the -roof. Profile your performance and memory usage when using these props. If you don't plan to move a view anymore, turn this property off.

    Animating the size of an image drops UI thread FPS #

    On iOS, each time you adjust the width or height of an Image component +roof. Profile your performance and memory usage when using these props. If you don't plan to move a view anymore, turn this property off.

    Animating the size of an image drops UI thread FPS #

    On iOS, each time you adjust the width or height of an Image component it is re-cropped and scaled from the original image. This can be very expensive, especially for large images. Instead, use the transform: [{scale}] style property to animate the size. An example of when you might do this is -when you tap an image and zoom it in to full screen.

    My TouchableX view isn't very responsive #

    Sometimes, if we do an action in the same frame that we are adjusting +when you tap an image and zoom it in to full screen.

    My TouchableX view isn't very responsive #

    Sometimes, if we do an action in the same frame that we are adjusting the opacity or highlight of a component that is responding to a touch, we won't see that effect until after the onPress function has returned. If onPress does a setState that results in a lot of work and a few @@ -183,9 +183,9 @@ inside of your onPress handler in requestAnimationFrame this.requestAnimationFrame(() => { this.doExpensiveAction(); }); -}

    Profiling #

    Use the built-in Profiler to get detailed information about work done in +}

    Profiling #

    Use the built-in Profiler to get detailed information about work done in the JavaScript thread and main thread side-by-side.

    For iOS, Instruments are an invaluable tool, and on Android you should -learn to use systrace.

    © 2015 Facebook Inc.

    Picker #

    Edit on GitHub

    Renders the native picker component on iOS and Android. Example:

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

    Picker #

    Edit on GitHub

    Renders the native picker component on iOS and Android. Example:

    <Picker selectedValue={this.state.language} onValueChange={(lang) => this.setState({language: lang})}> <Picker.Item label="Java" value="java" /> <Picker.Item label="JavaScript" value="js" /> -</Picker>

    Props #

    onValueChange function #

    Callback for when an item is selected. This is called with the following parameters: +</Picker>

    Props #

    onValueChange function #

    Callback for when an item is selected. This is called with the following parameters: - itemValue: the value prop of the item that was selected - - itemPosition: the index of the selected item in this picker

    selectedValue any #

    Value matching value of one of the items. Can be a string or an integer.

    style pickerStyleType #

    testID string #

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

    androidenabled bool #

    If set to false, the picker will be disabled, i.e. the user will not be able to make a -selection.

    androidmode enum('dialog', 'dropdown') #

    On Android, specifies how to display the selection items when the user taps on the picker:

    • 'dialog': Show a modal dialog. This is the default.
    • 'dropdown': Shows a dropdown anchored to the picker view

    androidprompt string #

    Prompt string for this picker, used on Android in dialog mode as the title of the dialog.

    iositemStyle itemStylePropType #

    Style to apply to each of the item labels.

    © 2015 Facebook Inc.

    PickerIOS #

    Edit on GitHub

    Props #

    itemStyle itemStylePropType #

    onValueChange function #

    selectedValue any #

    Examples #

    Edit on GitHub
    'use strict'; +PickerIOS – React Native | A framework for building native apps using React

    PickerIOS #

    Edit on GitHub

    Props #

    itemStyle itemStylePropType #

    onValueChange function #

    selectedValue any #

    Examples #

    Edit on GitHub
    'use strict'; var React = require('react-native'); var { @@ -137,7 +137,7 @@ exports.examples : function(): ReactElement { return <PickerStyleExample />; }, -}];
    © 2015 Facebook Inc.

    PixelRatio #

    Edit on GitHub

    PixelRatio class gives access to the device pixel density.

    Fetching a correctly sized image #

    You should get a higher resolution image if you are on a high pixel density +PixelRatio – React Native | A framework for building native apps using React

    PixelRatio #

    Edit on GitHub

    PixelRatio class gives access to the device pixel density.

    Fetching a correctly sized image #

    You should get a higher resolution image if you are on a high pixel density device. A good rule of thumb is to multiply the size of the image you display by the pixel ratio.

    var image = getImage({ width: PixelRatio.getPixelSizeForLayoutSize(200), height: PixelRatio.getPixelSizeForLayoutSize(100), }); -<Image source={image} style={{width: 200, height: 100}} />

    Methods #

    static get() #

    Returns the device pixel density. Some examples:

    • PixelRatio.get() === 1
      • mdpi Android devices (160 dpi)
    • PixelRatio.get() === 1.5
      • hdpi Android devices (240 dpi)
    • PixelRatio.get() === 2
      • iPhone 4, 4S
      • iPhone 5, 5c, 5s
      • iPhone 6
      • xhdpi Android devices (320 dpi)
    • PixelRatio.get() === 3
      • iPhone 6 plus
      • xxhdpi Android devices (480 dpi)
    • PixelRatio.get() === 3.5
      • Nexus 6

    static getFontScale() #

    Returns the scaling factor for font sizes. This is the ratio that is used to calculate the +<Image source={image} style={{width: 200, height: 100}} />

    Methods #

    static get() #

    Returns the device pixel density. Some examples:

    • PixelRatio.get() === 1
      • mdpi Android devices (160 dpi)
    • PixelRatio.get() === 1.5
      • hdpi Android devices (240 dpi)
    • PixelRatio.get() === 2
      • iPhone 4, 4S
      • iPhone 5, 5c, 5s
      • iPhone 6
      • xhdpi Android devices (320 dpi)
    • PixelRatio.get() === 3
      • iPhone 6 plus
      • xxhdpi Android devices (480 dpi)
    • PixelRatio.get() === 3.5
      • Nexus 6

    static getFontScale() #

    Returns the scaling factor for font sizes. This is the ratio that is used to calculate the absolute font size, so any elements that heavily depend on that should use this to do calculations.

    If a font scale is not set, this returns the device pixel ratio.

    Currently this is only implemented on Android and reflects the user preference set in Settings > Display > Font size, on iOS it will always return the default pixel ratio. -@platform android

    static getPixelSizeForLayoutSize(layoutSize: number) #

    Converts a layout size (dp) to pixel size (px).

    Guaranteed to return an integer number.

    static roundToNearestPixel(layoutSize: number) #

    Rounds a layout size (dp) to the nearest layout size that corresponds to +@platform android

    static getPixelSizeForLayoutSize(layoutSize: number) #

    Converts a layout size (dp) to pixel size (px).

    Guaranteed to return an integer number.

    static roundToNearestPixel(layoutSize: number) #

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

    static startDetecting() #

    // No-op for iOS, but used on the web. Should not be documented.

    Description #

    Edit on GitHub

    Pixel Grid Snapping #

    In iOS, you can specify positions and dimensions for elements with arbitrary precision, for example 29.674825. But, ultimately the physical display only have a fixed number of pixels, for example 640×960 for iphone 4 or 750×1334 for iphone 6. iOS tries to be as faithful as possible to the user value by spreading one original pixel into multiple ones to trick the eye. The downside of this technique is that it makes the resulting element look blurry.

    In practice, we found out that developers do not want this feature and they have to work around it by doing manual rounding in order to avoid having blurry elements. In React Native, we are rounding all the pixels automatically.

    We have to be careful when to do this rounding. You never want to work with rounded and unrounded values at the same time as you're going to accumulate rounding errors. Having even one rounding error is deadly because a one pixel border may vanish or be twice as big.

    In React Native, everything in JS and within the layout engine work with arbitrary precision numbers. It's only when we set the position and dimensions of the native element on the main thread that we round. Also, rounding is done relative to the root rather than the parent, again to avoid accumulating rounding errors.

    © 2015 Facebook Inc.

    Platform Specific Code #

    Edit on GitHub

    When building a cross-platform app, the need to write different code for different platforms may arise. This can always be achieved by organizing the various components in different folders:

    /common/components/ -/android/components/ +Platform Specific Code – React Native | A framework for building native apps using React

    Platform Specific Code #

    Edit on GitHub

    When building a cross-platform app, the need to write different code for different platforms may arise. This can always be achieved by organizing the various components in different folders:

    /common/components/ +/android/components/ /ios/components/

    Another option may be naming the components differently depending on the platform they are going to be used in:

    BigButtonIOS.js -BigButtonAndroid.js

    But React Native provides two alternatives to easily organize your code separating it by platform:

    Platform specific extensions #

    React Native will detect when a file has a .ios. or .android. extension and load the right file for each platform when requiring them from other components.

    For example, you can have these files in your project:

    BigButton.ios.js -BigButton.android.js

    With this setup, you can just require the files from a different component without paying attention to the platform in which the app will run.

    var BigButton = require('./components/BigButton');

    React Native will import the correct component for the running platform.

    Platform module #

    A module is provided by React Native to detect what is the platform in which the app is running. This piece of functionality can be useful when only small parts of a component are platform specific.

    var {Platform} = React; +BigButtonAndroid.js

    But React Native provides two alternatives to easily organize your code separating it by platform:

    Platform specific extensions #

    React Native will detect when a file has a .ios. or .android. extension and load the right file for each platform when requiring them from other components.

    For example, you can have these files in your project:

    BigButton.ios.js +BigButton.android.js

    With this setup, you can just require the files from a different component without paying attention to the platform in which the app will run.

    import BigButton from './components/BigButton';

    React Native will import the correct component for the running platform.

    Platform module #

    A module is provided by React Native to detect what is the platform in which the app is running. This piece of functionality can be useful when only small parts of a component are platform specific.

    var { Platform } = React; var styles = StyleSheet.create({ height: (Platform.OS === 'ios') ? 200 : 100, -});

    Platform.OS will be ios when running in iOS and android when running in an Android device or simulator.

    Detecting Android version #

    On Android, the Platform module can be also used to detect which is the version of the Android Platform in which the app is running

    var {Platform} = React; +});

    Platform.OS will be ios when running in iOS and android when running in an Android device or simulator.

    Detecting Android version #

    On Android, the Platform module can be also used to detect which is the version of the Android Platform in which the app is running

    var {Platform} = React; if(Platform.Version === '5.0'){ console.log('Running on Lollipop!'); -}
    © 2015 Facebook Inc.

    ProgressBarAndroid #

    Edit on GitHub

    React component that wraps the Android-only ProgressBar. This component is used to indicate +ProgressBarAndroid – React Native | A framework for building native apps using React

    ProgressBarAndroid #

    Edit on GitHub

    React component that wraps the Android-only ProgressBar. This component is used to indicate that the app is loading or there is some activity in the app.

    Example:

    render: function() { var progressBar = <View style={styles.container}> @@ -12,8 +12,8 @@ that the app is loading or there is some activity in the app.

    Example:

    style={styles.loadingComponent} /> ); -},

    Props #

    color color #

    Color of the progress bar.

    indeterminate indeterminateType #

    If the progress bar will show indeterminate progress. Note that this -can only be false if styleAttr is Horizontal.

    progress number #

    The progress value (between 0 and 1).

    styleAttr STYLE_ATTRIBUTES #

    Style of the ProgressBar. One of:

    • Horizontal
    • Normal (default)
    • Small
    • Large
    • Inverse
    • SmallInverse
    • LargeInverse

    testID string #

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

    Examples #

    Edit on GitHub
    'use strict'; +},

    Props #

    color color #

    Color of the progress bar.

    indeterminate indeterminateType #

    If the progress bar will show indeterminate progress. Note that this +can only be false if styleAttr is Horizontal.

    progress number #

    The progress value (between 0 and 1).

    styleAttr STYLE_ATTRIBUTES #

    Style of the ProgressBar. One of:

    • Horizontal
    • Normal (default)
    • Small
    • Large
    • Inverse
    • SmallInverse
    • LargeInverse

    testID string #

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

    Examples #

    Edit on GitHub
    'use strict'; var ProgressBar = require('ProgressBarAndroid'); var React = require('React'); @@ -108,7 +108,7 @@ can only be false if styleAttr is Horizontal.

    < }, }); -module.exports = ProgressBarAndroidExample;
    © 2015 Facebook Inc.

    ProgressViewIOS #

    Edit on GitHub

    Use ProgressViewIOS to render a UIProgressView on iOS.

    Props #

    progress number #

    The progress value (between 0 and 1).

    progressImage Image.propTypes.source #

    A stretchable image to display as the progress bar.

    progressTintColor string #

    The tint color of the progress bar itself.

    progressViewStyle enum('default', 'bar') #

    The progress bar style.

    trackImage Image.propTypes.source #

    A stretchable image to display behind the progress bar.

    trackTintColor string #

    The tint color of the progress bar track.

    Examples #

    Edit on GitHub
    'use strict'; +ProgressViewIOS – React Native | A framework for building native apps using React

    ProgressViewIOS #

    Edit on GitHub

    Use ProgressViewIOS to render a UIProgressView on iOS.

    Props #

    progress number #

    The progress value (between 0 and 1).

    progressImage Image.propTypes.source #

    A stretchable image to display as the progress bar.

    progressTintColor string #

    The tint color of the progress bar itself.

    progressViewStyle enum('default', 'bar') #

    The progress bar style.

    trackImage Image.propTypes.source #

    A stretchable image to display behind the progress bar.

    trackTintColor string #

    The tint color of the progress bar track.

    Examples #

    Edit on GitHub
    'use strict'; var React = require('react-native'); var { @@ -66,7 +66,7 @@ exports.examples : { marginTop: 20, } -});
    © 2015 Facebook Inc.

    PullToRefreshViewAndroid #

    Edit on GitHub

    React view that supports a single scrollable child view (e.g. ScrollView). When this child +PullToRefreshViewAndroid – React Native | A framework for building native apps using React

    PullToRefreshViewAndroid #

    Edit on GitHub

    React view that supports a single scrollable child view (e.g. ScrollView). When this child view is at scrollY: 0, swiping down triggers an onRefresh event.

    The style {flex: 1} might be required to ensure the expected behavior of the child component -(e.g. when the child is expected to scroll with ScrollView or ListView).

    Props #

    colors [[object Object]] #

    The colors (at least one) that will be used to draw the refresh indicator

    enabled bool #

    Whether the pull to refresh functionality is enabled

    progressBackgroundColor color #

    The background color of the refresh indicator

    refreshing bool #

    Whether the view should be indicating an active refresh

    size RefreshLayoutConsts.SIZE.DEFAULT #

    Size of the refresh indicator, see PullToRefreshViewAndroid.SIZE

    Examples #

    Edit on GitHub
    'use strict'; +(e.g. when the child is expected to scroll with ScrollView or ListView).

    Props #

    colors [[object Object]] #

    The colors (at least one) that will be used to draw the refresh indicator

    enabled bool #

    Whether the pull to refresh functionality is enabled

    progressBackgroundColor color #

    The background color of the refresh indicator

    refreshing bool #

    Whether the view should be indicating an active refresh

    size RefreshLayoutConsts.SIZE.DEFAULT #

    Size of the refresh indicator, see PullToRefreshViewAndroid.SIZE

    Examples #

    Edit on GitHub
    'use strict'; const React = require('react-native'); const { @@ -113,7 +113,7 @@ const PullToRefreshViewAndroidExample = Reac }); -module.exports = PullToRefreshViewAndroidExample;
    © 2015 Facebook Inc.

    PushNotificationIOS #

    Edit on GitHub

    Handle push notifications for your app, including permission handling and +PushNotificationIOS – React Native | A framework for building native apps using React

    PushNotificationIOS #

    Edit on GitHub

    Handle push notifications for your app, including permission handling and icon badge number.

    To get up and running, configure your notifications with Apple and your server-side system. To get an idea, this is the Parse guide.

    Manually link the PushNotificationIOS library

    • Be sure to add the following to your Header Search Paths: $(SRCROOT)/../node_modules/react-native/Libraries/PushNotificationIOS
    • Set the search to recursive

    Finally, to enable support for notification and register events you need to augment your AppDelegate.

    At the top of your AppDelegate.m:

    #import "RCTPushNotificationManager.h"

    And then in your AppDelegate implementation add the following:

    Methods #

    static presentLocalNotification(details: Object) #

    Schedules the localNotification for immediate presentation.

    details is an object containing:

    • alertBody : The message displayed in the notification alert.
    • soundName : The sound played when the notification is fired (optional).

    static scheduleLocalNotification(details: Object) #

    Schedules the localNotification for future presentation.

    details is an object containing:

    • fireDate : The date and time when the system should deliver the notification.
    • alertBody : The message displayed in the notification alert.
    • soundName : The sound played when the notification is fired (optional).

    static cancelAllLocalNotifications() #

    Cancels all scheduled localNotifications

    static setApplicationIconBadgeNumber(number: number) #

    Sets the badge number for the app icon on the home screen

    static getApplicationIconBadgeNumber(callback: Function) #

    Gets the current badge number for the app icon on the home screen

    static addEventListener(type: string, handler: Function) #

    Attaches a listener to remote notification events while the app is running + } + // Required for the localNotification event. + - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification + { + [RCTPushNotificationManager didReceiveLocalNotification:notification]; + }

    Methods #

    static presentLocalNotification(details: Object) #

    Schedules the localNotification for immediate presentation.

    details is an object containing:

    • alertBody : The message displayed in the notification alert.
    • soundName : The sound played when the notification is fired (optional).

    static scheduleLocalNotification(details: Object) #

    Schedules the localNotification for future presentation.

    details is an object containing:

    • fireDate : The date and time when the system should deliver the notification.
    • alertBody : The message displayed in the notification alert.
    • soundName : The sound played when the notification is fired (optional).
    • userInfo : An optional object containing additional notification data.

    static cancelAllLocalNotifications() #

    Cancels all scheduled localNotifications

    static setApplicationIconBadgeNumber(number: number) #

    Sets the badge number for the app icon on the home screen

    static getApplicationIconBadgeNumber(callback: Function) #

    Gets the current badge number for the app icon on the home screen

    static cancelLocalNotifications(userInfo: Object) #

    Cancel local notifications.

    Optionally restricts the set of canceled notifications to those +notifications whose userInfo fields match the corresponding fields +in the userInfo argument.

    static addEventListener(type: string, handler: Function) #

    Attaches a listener to remote notification events while the app is running in the foreground or the background.

    Valid events are:

    • notification : Fired when a remote notification is received. The handler will be invoked with an instance of PushNotificationIOS.
    • register: Fired when the user registers for remote notifications. The handler will be invoked with a hex string representing the deviceToken.

    static requestPermissions(permissions?: { alert?: boolean, badge?: boolean, sound?: boolean - }) #

    Requests notification permissions from iOS, prompting the user's + }) #

    Requests notification permissions from iOS, prompting the user's dialog box. By default, it will request all notification permissions, but a subset of these can be requested by passing a map of requested permissions. The following permissions are supported:

    • alert
    • badge
    • sound

    If a map is provided to the method, only the permissions with truthy values -will be requested.

    static abandonPermissions() #

    Unregister for all remote notifications received via Apple Push Notification service.

    You should call this method in rare circumstances only, such as when a new version of +will be requested.

    static abandonPermissions() #

    Unregister for all remote notifications received via Apple Push Notification service.

    You should call this method in rare circumstances only, such as when a new version of the app removes support for all types of remote notifications. Users can temporarily prevent apps from receiving remote notifications through the Notifications section of -the Settings app. Apps unregistered through this method can always re-register.

    static checkPermissions(callback: Function) #

    See what push permissions are currently enabled. callback will be -invoked with a permissions object:

    • alert :boolean
    • badge :boolean
    • sound :boolean

    static removeEventListener(type: string, handler: Function) #

    Removes the event listener. Do this in componentWillUnmount to prevent -memory leaks

    static popInitialNotification() #

    An initial notification will be available if the app was cold-launched +the Settings app. Apps unregistered through this method can always re-register.

    static checkPermissions(callback: Function) #

    See what push permissions are currently enabled. callback will be +invoked with a permissions object:

    • alert :boolean
    • badge :boolean
    • sound :boolean

    static removeEventListener(type: string, handler: Function) #

    Removes the event listener. Do this in componentWillUnmount to prevent +memory leaks

    static popInitialNotification() #

    An initial notification will be available if the app was cold-launched from a notification.

    The first caller of popInitialNotification will get the initial -notification object, or null. Subsequent invocations will return null.

    constructor(nativeNotif: Object) #

    You will never need to instantiate PushNotificationIOS yourself. +notification object, or null. Subsequent invocations will return null.

    constructor(nativeNotif: Object) #

    You will never need to instantiate PushNotificationIOS yourself. Listening to the notification event and invoking -popInitialNotification is sufficient

    getMessage() #

    An alias for getAlert to get the notification's main message string

    getSound() #

    Gets the sound string from the aps object

    getAlert() #

    Gets the notification's main message from the aps object

    getBadgeCount() #

    Gets the badge count number from the aps object

    getData() #

    Gets the data object on the notif

    Examples #

    Edit on GitHub
    'use strict'; +popInitialNotification is sufficient

    getMessage() #

    An alias for getAlert to get the notification's main message string

    getSound() #

    Gets the sound string from the aps object

    getAlert() #

    Gets the notification's main message from the aps object

    getBadgeCount() #

    Gets the badge count number from the aps object

    getData() #

    Gets the data object on the notif

    Examples #

    Edit on GitHub
    'use strict'; var React = require('react-native'); var { @@ -177,7 +184,7 @@ exports.examples render(): React.Component { return <NotificationPermissionExample />; } -}];
    © 2015 Facebook Inc.

    RefreshControl #

    Edit on GitHub

    This component is used inside a ScrollView to add pull to refresh +RefreshControl – React Native | A framework for building native apps using React

    RefreshControl #

    Edit on GitHub

    This component is used inside a ScrollView to add pull to refresh functionality. When the ScrollView is at scrollY: 0, swiping down -triggers an onRefresh event.

    Props #

    onRefresh function #

    Called when the view starts refreshing.

    refreshing bool #

    Whether the view should be indicating an active refresh.

    androidcolors [[object Object]] #

    The colors (at least one) that will be used to draw the refresh indicator.

    androidenabled bool #

    Whether the pull to refresh functionality is enabled.

    androidprogressBackgroundColor color #

    The background color of the refresh indicator.

    androidsize RefreshLayoutConsts.SIZE.DEFAULT #

    Size of the refresh indicator, see RefreshControl.SIZE.

    iostintColor color #

    The color of the refresh indicator.

    iostitle string #

    The title displayed under the refresh indicator.

    Examples #

    Edit on GitHub
    'use strict'; +triggers an onRefresh event.

    Props #

    onRefresh function #

    Called when the view starts refreshing.

    refreshing bool #

    Whether the view should be indicating an active refresh.

    androidcolors [[object Object]] #

    The colors (at least one) that will be used to draw the refresh indicator.

    androidenabled bool #

    Whether the pull to refresh functionality is enabled.

    androidprogressBackgroundColor color #

    The background color of the refresh indicator.

    androidsize RefreshLayoutConsts.SIZE.DEFAULT #

    Size of the refresh indicator, see RefreshControl.SIZE.

    iostintColor color #

    The color of the refresh indicator.

    iostitle string #

    The title displayed under the refresh indicator.

    Examples #

    Edit on GitHub
    'use strict'; const React = require('react-native'); const { @@ -110,7 +110,7 @@ const RefreshControlExample = React}, }); -module.exports = RefreshControlExample;
    © 2015 Facebook Inc.

    Running On Device #

    Edit on GitHub

    Prerequisite: USB Debugging #

    You'll need this in order to install your app on your device. First, make sure you have USB debugging enabled on your device.

    Check that your device has been successfully connected by running adb devices:

    $ adb devices +Running On Device – React Native | A framework for building native apps using React

    Running On Device #

    Edit on GitHub

    Prerequisite: USB Debugging #

    You'll need this in order to install your app on your device. First, make sure you have USB debugging enabled on your device.

    Check that your device has been successfully connected by running adb devices:

    $ adb devices List of devices attached emulator-5554 offline # Google emulator -14ed2fcc device # Physical device

    Seeing device in the right column means the device is connected. Android - go figure :) You must have only one device connected.

    Now you can use react-native run-android to install and launch your app on the device.

    Accessing development server from device #

    You can also iterate quickly on device using the development server. Follow one of the steps described below to make your development server running on your laptop accessible for your device.

    Hint

    Most modern android devices don't have a hardware menu button, which we use to trigger the developer menu. In that case you can shake the device to open the dev menu (to reload, debug, etc.). Alternatively, you can run the command adb shell input keyevent 82 to open the dev menu (82 being the Menu key code).

    Using adb reverse #

    Note that this option is available on devices running android 5.0+ (API 21).

    Have your device connected via USB with debugging enabled (see paragraph above on how to enable USB debugging on your device).

    1. Run adb reverse tcp:8081 tcp:8081
    2. You can use Reload JS and other development options with no extra configuration

    Configure your app to connect to the local dev server via Wi-Fi #

    1. Make sure your laptop and your phone are on the same Wi-Fi network.
    2. Open your React Native app on your device. You can do this the same way you'd open any other app.
    3. You'll see a red screen with an error. This is OK. The following steps will fix that.
    4. Open the Developer menu by shaking the device or running adb shell input keyevent 82 from the command line.
    5. Go to Dev Settings.
    6. Go to Debug server host for device.
    7. Type in your machine's IP address and the port of the local dev server (e.g. 10.0.1.1:8081). On Mac, you can find the IP address in System Preferences / Network. On Windows, open the command prompt and type ipconfig to find your machine's IP address (more info).
    8. Go back to the Developer menu and select Reload JS.
    © 2015 Facebook Inc.

    Running On Device #

    Edit on GitHub

    Note that running on device requires Apple Developer account and provisioning your iPhone. This guide covers only React Native specific topic.

    Accessing development server from device #

    You can iterate quickly on device using development server. To do that, your laptop and your phone have to be on the same wifi network.

    1. Open AwesomeApp/ios/AwesomeApp/AppDelegate.m
    2. Change the IP in the URL from localhost to your laptop's IP. On Mac, you can find the IP address in System Preferences / Network.
    3. In Xcode select your phone as build target and press "Build and run"

    Hint

    Shake the device to open development menu (reload, debug, etc.)

    Using offline bundle #

    When you run your app on device, we pack all the JavaScript code and the images used into the app's resources. This way you can test it without development server running and submit the app to the AppStore.

    1. Open AwesomeApp/ios/AwesomeApp/AppDelegate.m
    2. Uncomment jsCodeLocation = [[NSBundle mainBundle] ...
    3. The JS bundle will be built for dev or prod depending on your app's scheme (Debug = development build with warnings, Release = minified prod build with perf optimizations). To change the scheme navigate to Product > Scheme > Edit Scheme... in xcode and change Build Configuration between Debug and Release.

    Disabling in-app developer menu #

    When building your app for production, your app's scheme should be set to Release as detailed in the debugging documentation in order to disable the in-app developer menu.

    Troubleshooting #

    If curl command fails make sure the packager is running. Also try adding --ipv4 flag to the end of it.

    Note that since v0.14 JS and images are automatically packaged into the iOS app using Bundle React Native code and images Xcode build phase.

    © 2015 Facebook Inc.

    Running On Device #

    Edit on GitHub

    Note that running on device requires Apple Developer account and provisioning your iPhone. This guide covers only React Native specific topic.

    Accessing development server from device #

    You can iterate quickly on device using development server. To do that, your laptop and your phone have to be on the same wifi network.

    1. Open AwesomeApp/ios/AwesomeApp/AppDelegate.m
    2. Change the IP in the URL from localhost to your laptop's IP. On Mac, you can find the IP address in System Preferences / Network.
    3. In Xcode select your phone as build target and press "Build and run"

    Hint

    Shake the device to open development menu (reload, debug, etc.)

    Using offline bundle #

    When you run your app on device, we pack all the JavaScript code and the images used into the app's resources. This way you can test it without development server running and submit the app to the AppStore.

    1. Open AwesomeApp/ios/AwesomeApp/AppDelegate.m
    2. Uncomment jsCodeLocation = [[NSBundle mainBundle] ...
    3. The JS bundle will be built for dev or prod depending on your app's scheme (Debug = development build with warnings, Release = minified prod build with perf optimizations). To change the scheme navigate to Product > Scheme > Edit Scheme... in xcode and change Build Configuration between Debug and Release.

    Disabling in-app developer menu #

    When building your app for production, your app's scheme should be set to Release as detailed in the debugging documentation in order to disable the in-app developer menu.

    Troubleshooting #

    If curl command fails make sure the packager is running. Also try adding --ipv4 flag to the end of it.

    Note that since v0.14 JS and images are automatically packaged into the iOS app using Bundle React Native code and images Xcode build phase.

    © 2016 Facebook Inc.

    ScrollView #

    Edit on GitHub

    Component that wraps platform ScrollView while providing +ScrollView – React Native | A framework for building native apps using React

    ScrollView #

    Edit on GitHub

    Component that wraps platform ScrollView while providing integration with touch locking "responder" system.

    Keep in mind that ScrollViews must have a bounded height in order to work, since they contain unbounded-height children into a bounded container (via a scroll interaction). In order to bound the height of a ScrollView, either @@ -6,7 +6,7 @@ set the height of the view directly (discouraged) or make sure all parent views have bounded height. Forgetting to transfer {flex: 1} down the view stack can lead to errors here, which the element inspector makes easy to debug.

    Doesn't yet support other contained responders from blocking this scroll -view from becoming the responder.

    Props #

    contentContainerStyle StyleSheetPropType(ViewStylePropTypes) #

    These styles will be applied to the scroll view content container which +view from becoming the responder.

    Props #

    contentContainerStyle StyleSheetPropType(ViewStylePropTypes) #

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

    return ( <ScrollView contentContainerStyle={styles.contentContainer}> </ScrollView> @@ -16,77 +16,77 @@ wraps all of the child views. Example:

    return ( contentContainer: { paddingVertical: 20 } - });

    horizontal bool #

    When true, the scroll view's children are arranged horizontally in a row -instead of vertically in a column. The default value is false.

    keyboardDismissMode enum('none', 'interactive', 'on-drag') #

    Determines whether the keyboard gets dismissed in response to a drag. + });

    horizontal bool #

    When true, the scroll view's children are arranged horizontally in a row +instead of vertically in a column. The default value is false.

    keyboardDismissMode enum('none', 'interactive', 'on-drag') #

    Determines whether the keyboard gets dismissed in response to a drag. - 'none' (the default), drags do not dismiss the keyboard. - 'on-drag', the keyboard is dismissed when a drag begins. - 'interactive', the keyboard is dismissed interactively with the drag and moves in synchrony with the touch; dragging upwards cancels the dismissal. - On android this is not supported and it will have the same behavior as 'none'.

    keyboardShouldPersistTaps bool #

    When false, tapping outside of the focused text input when the keyboard + On android this is not supported and it will have the same behavior as 'none'.

    keyboardShouldPersistTaps bool #

    When false, tapping outside of the focused text input when the keyboard is up dismisses the keyboard. When true, the scroll view will not catch taps, and the keyboard will not dismiss automatically. The default value -is false.

    onContentSizeChange function #

    Called when scrollable content view of the ScrollView changes. It's +is false.

    onContentSizeChange function #

    Called when scrollable content view of the ScrollView changes. It's implemented using onLayout handler attached to the content container -which this ScrollView renders.

    onScroll function #

    Fires at most once per frame during scrolling. The frequency of the -events can be controlled using the scrollEventThrottle prop.

    refreshControl element #

    A RefreshControl component, used to provide pull-to-refresh -functionality for the ScrollView.

    See RefreshControl.

    removeClippedSubviews bool #

    Experimental: When true, offscreen child views (whose overflow value is +which this ScrollView renders.

    onScroll function #

    Fires at most once per frame during scrolling. The frequency of the +events can be controlled using the scrollEventThrottle prop.

    refreshControl element #

    A RefreshControl component, used to provide pull-to-refresh +functionality for the ScrollView.

    See RefreshControl.

    removeClippedSubviews bool #

    Experimental: When true, offscreen child views (whose overflow value is hidden) are removed from their native backing superview when offscreen. This can improve scrolling performance on long lists. The default value is -true.

    scrollEnabled bool #

    When false, the content does not scroll. -The default value is true.

    showsHorizontalScrollIndicator bool #

    When true, shows a horizontal scroll indicator.

    showsVerticalScrollIndicator bool #

    When true, shows a vertical scroll indicator.

    style style #

    backfaceVisibility enum('visible', 'hidden')
    backgroundColor color
    borderBottomColor color
    borderBottomLeftRadius number
    borderBottomRightRadius number
    borderBottomWidth number
    borderColor color
    borderLeftColor color
    borderLeftWidth number
    borderRadius number
    borderRightColor color
    borderRightWidth number
    borderStyle enum('solid', 'dotted', 'dashed')
    borderTopColor color
    borderTopLeftRadius number
    borderTopRightRadius number
    borderTopWidth number
    borderWidth number
    opacity number
    overflow enum('visible', 'hidden')
    androidelevation number

    (Android-only) Sets the elevation of a view, using Android's underlying +true.

    scrollEnabled bool #

    When false, the content does not scroll. +The default value is true.

    showsHorizontalScrollIndicator bool #

    When true, shows a horizontal scroll indicator.

    showsVerticalScrollIndicator bool #

    When true, shows a vertical scroll indicator.

    style style #

    backfaceVisibility enum('visible', 'hidden')
    backgroundColor color
    borderBottomColor color
    borderBottomLeftRadius number
    borderBottomRightRadius number
    borderBottomWidth number
    borderColor color
    borderLeftColor color
    borderLeftWidth number
    borderRadius number
    borderRightColor color
    borderRightWidth number
    borderStyle enum('solid', 'dotted', 'dashed')
    borderTopColor color
    borderTopLeftRadius number
    borderTopRightRadius number
    borderTopWidth number
    borderWidth number
    opacity number
    overflow enum('visible', 'hidden')
    androidelevation number

    (Android-only) Sets the elevation of a view, using Android's underlying elevation API. This adds a drop shadow to the item and affects z-order for overlapping views. -Only supported on Android 5.0+, has no effect on earlier versions.

    androidsendMomentumEvents bool #

    When true, momentum events will be sent from Android +Only supported on Android 5.0+, has no effect on earlier versions.

    androidsendMomentumEvents bool #

    When true, momentum events will be sent from Android This is internal and set automatically by the framework if you have -onMomentumScrollBegin or onMomentumScrollEnd set on your ScrollView

    iosalwaysBounceHorizontal bool #

    When true, the scroll view bounces horizontally when it reaches the end +onMomentumScrollBegin or onMomentumScrollEnd set on your ScrollView

    iosalwaysBounceHorizontal bool #

    When true, the scroll view bounces horizontally when it reaches the end even if the content is smaller than the scroll view itself. The default -value is true when horizontal={true} and false otherwise.

    iosalwaysBounceVertical bool #

    When true, the scroll view bounces vertically when it reaches the end +value is true when horizontal={true} and false otherwise.

    iosalwaysBounceVertical bool #

    When true, the scroll view bounces vertically when it reaches the end even if the content is smaller than the scroll view itself. The default -value is false when horizontal={true} and true otherwise.

    iosautomaticallyAdjustContentInsets bool #

    Controls whether iOS should automatically adjust the content inset +value is false when horizontal={true} and true otherwise.

    iosautomaticallyAdjustContentInsets bool #

    Controls whether iOS should automatically adjust the content inset for scroll views that are placed behind a navigation bar or -tab bar/ toolbar. The default value is true.

    iosbounces bool #

    When true, the scroll view bounces when it reaches the end of the +tab bar/ toolbar. The default value is true.

    iosbounces bool #

    When true, the scroll view bounces when it reaches the end of the content if the content is larger then the scroll view along the axis of the scroll direction. When false, it disables all bouncing even if -the alwaysBounce* props are true. The default value is true.

    iosbouncesZoom bool #

    When true, gestures can drive zoom past min/max and the zoom will animate +the alwaysBounce* props are true. The default value is true.

    iosbouncesZoom bool #

    When true, gestures can drive zoom past min/max and the zoom will animate to the min/max value at gesture end, otherwise the zoom will not exceed -the limits.

    ioscanCancelContentTouches bool #

    When false, once tracking starts, won't try to drag if the touch moves. -The default value is true.

    ioscenterContent bool #

    When true, the scroll view automatically centers the content when the +the limits.

    ioscanCancelContentTouches bool #

    When false, once tracking starts, won't try to drag if the touch moves. +The default value is true.

    ioscenterContent bool #

    When true, the scroll view automatically centers the content when the content is smaller than the scroll view bounds; when the content is larger than the scroll view, this property has no effect. The default -value is false.

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

    The amount by which the scroll view content is inset from the edges -of the scroll view. Defaults to {0, 0, 0, 0}.

    ioscontentOffset PointPropType #

    Used to manually set the starting scroll offset. -The default value is {x: 0, y: 0}.

    iosdecelerationRate enum('fast', 'normal'), number #

    A floating-point number that determines how quickly the scroll view +value is false.

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

    The amount by which the scroll view content is inset from the edges +of the scroll view. Defaults to {0, 0, 0, 0}.

    ioscontentOffset PointPropType #

    Used to manually set the starting scroll offset. +The default value is {x: 0, y: 0}.

    iosdecelerationRate enum('fast', 'normal'), number #

    A floating-point number that determines how quickly the scroll view decelerates after the user lifts their finger. You may also use string shortcuts "normal" and "fast" which match the underlying iOS settings for UIScrollViewDecelerationRateNormal and UIScrollViewDecelerationRateFast respectively. - Normal: 0.998 (the default) - - Fast: 0.9

    iosdirectionalLockEnabled bool #

    When true, the ScrollView will try to lock to only vertical or horizontal -scrolling while dragging. The default value is false.

    iosindicatorStyle enum('default', 'black', 'white') #

    The style of the scroll indicators. + - Fast: 0.9

    iosdirectionalLockEnabled bool #

    When true, the ScrollView will try to lock to only vertical or horizontal +scrolling while dragging. The default value is false.

    iosindicatorStyle enum('default', 'black', 'white') #

    The style of the scroll indicators. - default (the default), same as black. - black, scroll indicator is black. This style is good against a white content background. - - white, scroll indicator is white. This style is good against a black content background.

    iosmaximumZoomScale number #

    The maximum allowed zoom scale. The default value is 1.0.

    iosminimumZoomScale number #

    The minimum allowed zoom scale. The default value is 1.0.

    iosonRefreshStart function #

    Deprecated

    Use the refreshControl prop instead.

    iosonScrollAnimationEnd function #

    Called when a scrolling animation ends.

    iospagingEnabled bool #

    When true, the scroll view stops on multiples of the scroll view's size + - white, scroll indicator is white. This style is good against a black content background.

    iosmaximumZoomScale number #

    The maximum allowed zoom scale. The default value is 1.0.

    iosminimumZoomScale number #

    The minimum allowed zoom scale. The default value is 1.0.

    iosonRefreshStart function #

    Deprecated

    Use the refreshControl prop instead.

    iosonScrollAnimationEnd function #

    Called when a scrolling animation ends.

    iospagingEnabled bool #

    When true, the scroll view stops on multiples of the scroll view's size when scrolling. This can be used for horizontal pagination. The default -value is false.

    iosscrollEventThrottle number #

    This controls how often the scroll event will be fired while scrolling +value is false.

    iosscrollEventThrottle number #

    This controls how often the scroll event will be fired while scrolling (in events per seconds). A higher number yields better accuracy for code that is tracking the scroll position, but can lead to scroll performance problems due to the volume of information being send over the bridge. The default value is zero, which means the scroll event will be sent -only once each time the view is scrolled.

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

    The amount by which the scroll view indicators are inset from the edges +only once each time the view is scrolled.

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

    The amount by which the scroll view indicators are inset from the edges of the scroll view. This should normally be set to the same value as -the contentInset. Defaults to {0, 0, 0, 0}.

    iosscrollsToTop bool #

    When true, the scroll view scrolls to top when the status bar is tapped. -The default value is true.

    iossnapToAlignment enum('start', 'center', 'end') #

    When snapToInterval is set, snapToAlignment will define the relationship -of the the snapping to the scroll view. +the contentInset. Defaults to {0, 0, 0, 0}.

    iosscrollsToTop bool #

    When true, the scroll view scrolls to top when the status bar is tapped. +The default value is true.

    iossnapToAlignment enum('start', 'center', 'end') #

    When snapToInterval is set, snapToAlignment will define the relationship +of the snapping to the scroll view. - start (the default) will align the snap at the left (horizontal) or top (vertical) - center will align the snap in the center - - end will align the snap at the right (horizontal) or bottom (vertical)

    iossnapToInterval number #

    When set, causes the scroll view to stop at multiples of the value of + - end will align the snap at the right (horizontal) or bottom (vertical)

    iossnapToInterval number #

    When set, causes the scroll view to stop at multiples of the value of snapToInterval. This can be used for paginating through children that have lengths smaller than the scroll view. Used in combination -with snapToAlignment.

    iosstickyHeaderIndices [number] #

    An array of child indices determining which children get docked to the +with snapToAlignment.

    iosstickyHeaderIndices [number] #

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

    ioszoomScale number #

    The current scale of the scroll view content. The default value is 1.0.

    Examples #

    Edit on GitHub
    'use strict'; +with horizontal={true}.

    ioszoomScale number #

    The current scale of the scroll view content. The default value is 1.0.

    Examples #

    Edit on GitHub
    'use strict'; var React = require('react-native'); var { @@ -203,7 +203,7 @@ THUMBS = THUMBS: 64, height: 64, } -});
    © 2015 Facebook Inc.

    SegmentedControlIOS #

    Edit on GitHub

    Use SegmentedControlIOS to render a UISegmentedControl iOS.

    Props #

    enabled bool #

    If false the user won't be able to interact with the control. -Default value is true.

    momentary bool #

    If true, then selecting a segment won't persist visually. -The onValueChange callback will still work as expected.

    onChange function #

    Callback that is called when the user taps a segment; -passes the event as an argument

    onValueChange function #

    Callback that is called when the user taps a segment; -passes the segment's value as an argument

    selectedIndex number #

    The index in props.values of the segment to be pre-selected

    tintColor string #

    Accent color of the control.

    values [string] #

    The labels for the control's segment buttons, in order.

    Examples #

    Edit on GitHub
    'use strict'; +SegmentedControlIOS – React Native | A framework for building native apps using React

    SegmentedControlIOS #

    Edit on GitHub

    Use SegmentedControlIOS to render a UISegmentedControl iOS.

    Props #

    enabled bool #

    If false the user won't be able to interact with the control. +Default value is true.

    momentary bool #

    If true, then selecting a segment won't persist visually. +The onValueChange callback will still work as expected.

    onChange function #

    Callback that is called when the user taps a segment; +passes the event as an argument

    onValueChange function #

    Callback that is called when the user taps a segment; +passes the segment's value as an argument

    selectedIndex number #

    The index in props.values of the segment to be pre-selected

    tintColor string #

    Accent color of the control.

    values [string] #

    The labels for the control's segment buttons, in order.

    Examples #

    Edit on GitHub
    'use strict'; var React = require('react-native'); var { @@ -155,7 +155,7 @@ exports.examples : 'Change events can be detected', render(): ReactElement { return <EventSegmentedControlExample />; } } -];
    © 2015 Facebook Inc.

    ShadowPropTypesIOS #

    Edit on GitHub

    Props #

    shadowColor color #

    shadowOffset {width: number, height: number} #

    shadowOpacity number #

    shadowRadius number #

    © 2016 Facebook Inc.
    \ No newline at end of file diff --git a/docs/signed-apk-android.html b/docs/signed-apk-android.html index b8d62206cc7..cd55e1c6e36 100644 --- a/docs/signed-apk-android.html +++ b/docs/signed-apk-android.html @@ -1,7 +1,7 @@ -Generating Signed APK – React Native | A framework for building native apps using React

    Generating Signed APK #

    Edit on GitHub

    To distribute your Android application via Google Play store, you'll need to generate a signed release APK. The Signing Your Applications page on Android Developers documentation describes the topic in detail. This guide covers the process in brief, as well as lists the steps required to packaging the JavaScript bundle.

    Generating a signing key #

    You can generate a private signing key using keytool.

    $ keytool -genkey -v -keystore my-release-key.keystore -alias my-key-alias -keyalg RSA -keysize 2048 -validity 10000

    This command prompts you for passwords for the keystore and key, and to provide the Distinguished Name fields for your key. It then generates the keystore as a file called my-release-key.keystore.

    The keystore contains a single key, valid for 10000 days. The alias is a name that you will use later when signing your app, so remember to take note of the alias.

    Note: Remember to keep your keystore file private and never commit it to version control.

    Setting up gradle variables #

    1. Place the my-release-key.keystore file under the android/app directory in your project folder.
    2. Edit the file ~/.gradle/gradle.properties and add the following (replace ***** with the correct keystore password, alias and key password),
    MYAPP_RELEASE_STORE_FILE=my-release-key.keystore +Generating Signed APK – React Native | A framework for building native apps using React

    Generating Signed APK #

    Edit on GitHub

    To distribute your Android application via Google Play store, you'll need to generate a signed release APK. The Signing Your Applications page on Android Developers documentation describes the topic in detail. This guide covers the process in brief, as well as lists the steps required to packaging the JavaScript bundle.

    Generating a signing key #

    You can generate a private signing key using keytool.

    $ keytool -genkey -v -keystore my-release-key.keystore -alias my-key-alias -keyalg RSA -keysize 2048 -validity 10000

    This command prompts you for passwords for the keystore and key, and to provide the Distinguished Name fields for your key. It then generates the keystore as a file called my-release-key.keystore.

    The keystore contains a single key, valid for 10000 days. The alias is a name that you will use later when signing your app, so remember to take note of the alias.

    Note: Remember to keep your keystore file private and never commit it to version control.

    Setting up gradle variables #

    1. Place the my-release-key.keystore file under the android/app directory in your project folder.
    2. Edit the file ~/.gradle/gradle.properties and add the following (replace ***** with the correct keystore password, alias and key password),
    MYAPP_RELEASE_STORE_FILE=my-release-key.keystore MYAPP_RELEASE_KEY_ALIAS=my-key-alias MYAPP_RELEASE_STORE_PASSWORD=***** -MYAPP_RELEASE_KEY_PASSWORD=*****

    These are going to be global gradle variables, which we can later use in our gradle config to sign our app.

    Note: Once you publish the app on the Play Store, you will need to republish your app under a different package name (loosing all downloads and ratings) if you want to change the signing key at any point. So backup your keystore and don't forget the passwords.

    Adding signing config to your app's gradle config #

    Edit the file android/app/build.gradle in your project folder and add the signing config,

    ... +MYAPP_RELEASE_KEY_PASSWORD=*****

    These are going to be global gradle variables, which we can later use in our gradle config to sign our app.

    Note: Once you publish the app on the Play Store, you will need to republish your app under a different package name (loosing all downloads and ratings) if you want to change the signing key at any point. So backup your keystore and don't forget the passwords.

    Adding signing config to your app's gradle config #

    Edit the file android/app/build.gradle in your project folder and add the signing config,

    ... android { ... defaultConfig { ... } @@ -20,11 +20,11 @@ android { } } } -...

    Generating the release APK #

    If you have a react.gradle file in android/app #

    Simply run the following in a terminal:

    $ cd android && ./gradlew assembleRelease

    If you need to change the way the JavaScript bundle and/or drawable resources are bundled (e.g. if you changed the default file/folder names or the general structure of the project), have a look at android/app/build.gradle to see how you can update it to reflect these changes.

    If you don't have a react.gradle file: #

    You can upgrade to the latest version of React Native to get this file. Alternatively, you can bundle the JavaScript package and drawable resources manually by doing the following in a terminal:

    $ mkdir -p android/app/src/main/assets +...

    Generating the release APK #

    If you have a react.gradle file in android/app #

    Simply run the following in a terminal:

    $ cd android && ./gradlew assembleRelease

    If you need to change the way the JavaScript bundle and/or drawable resources are bundled (e.g. if you changed the default file/folder names or the general structure of the project), have a look at android/app/build.gradle to see how you can update it to reflect these changes.

    If you don't have a react.gradle file: #

    You can upgrade to the latest version of React Native to get this file. Alternatively, you can bundle the JavaScript package and drawable resources manually by doing the following in a terminal:

    $ mkdir -p android/app/src/main/assets $ react-native bundle --platform android --dev false --entry-file index.android.js \ --bundle-output android/app/src/main/assets/index.android.bundle \ --assets-dest android/app/src/main/res/ -$ cd android && ./gradlew assembleRelease

    In both cases the generated APK can be found under android/app/build/outputs/apk/app-release.apk, and is ready to be distributed.

    Testing the release build of your app #

    Before uploading the release build to the Play Store, make sure you test it thoroughly. Install it on the device using:

    $ cd android && ./gradlew installRelease

    Note that installRelease is only available if you've set up signing as described above.

    You can kill any running packager instances, all your and framework JavaScript code is bundled in the APK's assets.

    Enabling Proguard to reduce the size of the APK (optional) #

    Proguard is a tool that can slightly reduce the size of the APK. It does this by stripping parts of the React Native Java bytecode (and its dependencies) that your app is not using.

    IMPORTANT: Make sure to thoroughly test your app if you've enabled Proguard. Proguard often requires configuration specific to each native library you're using. See app/proguard-rules.pro.

    To enable Proguard, set minifyEnabled to true:

    ... +$ cd android && ./gradlew assembleRelease

    In both cases the generated APK can be found under android/app/build/outputs/apk/app-release.apk, and is ready to be distributed.

    Testing the release build of your app #

    Before uploading the release build to the Play Store, make sure you test it thoroughly. Install it on the device using:

    $ cd android && ./gradlew installRelease

    Note that installRelease is only available if you've set up signing as described above.

    You can kill any running packager instances, all your and framework JavaScript code is bundled in the APK's assets.

    Enabling Proguard to reduce the size of the APK (optional) #

    Proguard is a tool that can slightly reduce the size of the APK. It does this by stripping parts of the React Native Java bytecode (and its dependencies) that your app is not using.

    IMPORTANT: Make sure to thoroughly test your app if you've enabled Proguard. Proguard often requires configuration specific to each native library you're using. See app/proguard-rules.pro.

    To enable Proguard, set minifyEnabled to true:

    ... android { ... buildTypes { @@ -34,7 +34,7 @@ android { } } } -...
    © 2015 Facebook Inc.

    SliderIOS #

    Edit on GitHub

    Props #

    disabled bool #

    If true the user won't be able to move the slider. -Default value is false.

    maximumTrackImage Image.propTypes.source #

    Assigns a maximum track image. Only static images are supported. The -leftmost pixel of the image will be stretched to fill the track.

    maximumTrackTintColor string #

    The color used for the track to the right of the button. Overrides the -default blue gradient image.

    maximumValue number #

    Initial maximum value of the slider. Default value is 1.

    minimumTrackImage Image.propTypes.source #

    Assigns a minimum track image. Only static images are supported. The -rightmost pixel of the image will be stretched to fill the track.

    minimumTrackTintColor string #

    The color used for the track to the left of the button. Overrides the -default blue gradient image.

    minimumValue number #

    Initial minimum value of the slider. Default value is 0.

    onSlidingComplete function #

    Callback called when the user finishes changing the value (e.g. when -the slider is released).

    onValueChange function #

    Callback continuously called while the user is dragging the slider.

    step number #

    Step value of the slider. The value should be +SliderIOS – React Native | A framework for building native apps using React

    SliderIOS #

    Edit on GitHub

    Props #

    disabled bool #

    If true the user won't be able to move the slider. +Default value is false.

    maximumTrackImage Image.propTypes.source #

    Assigns a maximum track image. Only static images are supported. The +leftmost pixel of the image will be stretched to fill the track.

    maximumTrackTintColor string #

    The color used for the track to the right of the button. Overrides the +default blue gradient image.

    maximumValue number #

    Initial maximum value of the slider. Default value is 1.

    minimumTrackImage Image.propTypes.source #

    Assigns a minimum track image. Only static images are supported. The +rightmost pixel of the image will be stretched to fill the track.

    minimumTrackTintColor string #

    The color used for the track to the left of the button. Overrides the +default blue gradient image.

    minimumValue number #

    Initial minimum value of the slider. Default value is 0.

    onSlidingComplete function #

    Callback called when the user finishes changing the value (e.g. when +the slider is released).

    onValueChange function #

    Callback continuously called while the user is dragging the slider.

    step number #

    Step value of the slider. The value should be between 0 and (maximumValue - minimumValue). -Default value is 0.

    style View#style #

    Used to style and layout the Slider. See StyleSheet.js and -ViewStylePropTypes.js for more info.

    thumbImage Image.propTypes.source #

    Sets an image for the thumb. It only supports static images.

    trackImage Image.propTypes.source #

    Assigns a single image for the track. Only static images are supported. -The center pixel of the image will be stretched to fill the track.

    value number #

    Initial value of the slider. The value should be between minimumValue +Default value is 0.

    style View#style #

    Used to style and layout the Slider. See StyleSheet.js and +ViewStylePropTypes.js for more info.

    thumbImage Image.propTypes.source #

    Sets an image for the thumb. It only supports static images.

    trackImage Image.propTypes.source #

    Assigns a single image for the track. Only static images are supported. +The center pixel of the image will be stretched to fill the track.

    value number #

    Initial value of the slider. The value should be between minimumValue and maximumValue, which default to 0 and 1 respectively. Default value is 0.

    This is not a controlled component, e.g. if you don't update -the value, the component won't be reset to its initial value.

    Examples #

    Edit on GitHub
    'use strict'; +the value, the component won't be reset to its initial value.

    Examples #

    Edit on GitHub
    'use strict'; var React = require('react-native'); var { @@ -116,7 +116,7 @@ exports.examples ); } }, -];
    © 2015 Facebook Inc.

    StatusBar #

    Edit on GitHub

    Component to control the app status bar.

    Usage with Navigator #

    It is possible to have multiple StatusBar components mounted at the same +StatusBar – React Native | A framework for building native apps using React

    StatusBar #

    Edit on GitHub

    Component to control the app status bar.

    Usage with Navigator #

    It is possible to have multiple StatusBar components mounted at the same time. The props will be merged in the order the StatusBar components were mounted. One use case is to specify status bar styles per route using Navigator.

    <View> <StatusBar @@ -14,11 +14,11 @@ mounted. One use case is to specify status bar styles per route using Navi </View> } /> - </View>

    Props #

    animated bool #

    If the transition between status bar property changes should be animated. -Supported for backgroundColor, barStyle and hidden.

    hidden bool #

    If the status bar is hidden.

    androidbackgroundColor color #

    The background color of the status bar.

    androidtranslucent bool #

    If the status bar is translucent. + </View>

    Props #

    animated bool #

    If the transition between status bar property changes should be animated. +Supported for backgroundColor, barStyle and hidden.

    hidden bool #

    If the status bar is hidden.

    androidbackgroundColor color #

    The background color of the status bar.

    androidtranslucent bool #

    If the status bar is translucent. When translucent is set to true, the app will draw under the status bar. -This is useful when using a semi transparent status bar color.

    iosbarStyle enum('default', 'light-content') #

    Sets the color of the status bar text.

    iosnetworkActivityIndicatorVisible bool #

    If the network activity indicator should be visible.

    iosshowHideTransition enum('fade', 'slide') #

    The transition effect when showing and hiding the status bar using the hidden -prop. Defaults to 'fade'.

    Examples #

    Edit on GitHub
    'use strict'; +This is useful when using a semi transparent status bar color.

    iosbarStyle enum('default', 'light-content') #

    Sets the color of the status bar text.

    iosnetworkActivityIndicatorVisible bool #

    If the network activity indicator should be visible.

    iosshowHideTransition enum('fade', 'slide') #

    The transition effect when showing and hiding the status bar using the hidden +prop. Defaults to 'fade'.

    Examples #

    Edit on GitHub
    'use strict'; const React = require('react-native'); const { @@ -208,7 +208,7 @@ exports.examples : 8, fontWeight: 'bold', } -});
    © 2015 Facebook Inc.

    StatusBarIOS #

    Edit on GitHub

    Methods #

    static setStyle(style: StatusBarStyle, animated?: boolean) #

    static setHidden(hidden: boolean, animation?: StatusBarAnimation) #

    static setNetworkActivityIndicatorVisible(visible: boolean) #

    Examples #

    Edit on GitHub
    'use strict'; +StatusBarIOS – React Native | A framework for building native apps using React

    StatusBarIOS #

    Edit on GitHub

    Methods #

    static setStyle(style: StatusBarStyle, animated?: boolean) #

    static setHidden(hidden: boolean, animation?: StatusBarAnimation) #

    static setNetworkActivityIndicatorVisible(visible: boolean) #

    Examples #

    Edit on GitHub
    'use strict'; var React = require('react-native'); var { @@ -99,7 +99,7 @@ exports.examples : '#eeeeee', padding: 10, }, -});
    © 2015 Facebook Inc.

    Style #

    Edit on GitHub

    React Native doesn't implement CSS but instead relies on JavaScript to let you style your application. This has been a controversial decision and you can read through those slides for the rationale behind it.

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

    Style #

    Edit on GitHub

    React Native doesn't implement CSS but instead relies on JavaScript to let you style your application. This has been a controversial decision and you can read through those slides for the rationale behind it.

    -

    Declare Styles #

    The way to declare styles in React Native is the following:

    var styles = StyleSheet.create({ +

    Declare Styles #

    The way to declare styles in React Native is the following:

    var styles = StyleSheet.create({ base: { width: 38, height: 38, @@ -12,13 +12,13 @@ borderWidth: 2, borderColor: '#00ff00', }, -});

    StyleSheet.create construct is optional but provides some key advantages. It ensures that the values are immutable and opaque by transforming them into plain numbers that reference an internal table. By putting it at the end of the file, you also ensure that they are only created once for the application and not on every render.

    All the attribute names and values are a subset of what works on the web. For layout, React Native implements Flexbox.

    Using Styles #

    All the core components accept a style attribute.

    <Text style={styles.base} /> +});

    StyleSheet.create construct is optional but provides some key advantages. It ensures that the values are immutable and opaque by transforming them into plain numbers that reference an internal table. By putting it at the end of the file, you also ensure that they are only created once for the application and not on every render.

    All the attribute names and values are a subset of what works on the web. For layout, React Native implements Flexbox.

    Using Styles #

    All the core components accept a style attribute.

    <Text style={styles.base} /> <View style={styles.background} />

    They also accept an array of styles.

    <View style={[styles.base, styles.background]} />

    The behavior is the same as Object.assign: in case of conflicting values, the one from the right-most element will have precedence and falsy values like false, undefined and null will be ignored. A common pattern is to conditionally add a style based on some condition.

    <View style={[styles.base, this.state.active && styles.active]} />

    Finally, if you really have to, you can also create style objects in render, but they are highly discouraged. Put them last in the array definition.

    <View style={[styles.base, { width: this.state.width, height: this.state.width * this.state.aspectRatio }]} -/>

    Pass Styles Around #

    In order to let a call site customize the style of your component children, you can pass styles around. Use View.propTypes.style and Text.propTypes.style in order to make sure only styles are being passed.

    var List = React.createClass({ +/>

    Pass Styles Around #

    In order to let a call site customize the style of your component children, you can pass styles around. Use View.propTypes.style and Text.propTypes.style in order to make sure only styles are being passed.

    var List = React.createClass({ propTypes: { style: View.propTypes.style, elementStyle: View.propTypes.style, @@ -35,7 +35,7 @@ }); // ... in another file ... -<List style={styles.list} elementStyle={styles.listElement} />

    Supported Properties #

    You can checkout latest support of CSS Properties in following Links.

    © 2015 Facebook Inc.

    StyleSheet #

    Edit on GitHub

    A StyleSheet is an abstraction similar to CSS StyleSheets

    Create a new StyleSheet:

    var styles = StyleSheet.create({ +StyleSheet – React Native | A framework for building native apps using React

    StyleSheet #

    Edit on GitHub

    A StyleSheet is an abstraction similar to CSS StyleSheets

    Create a new StyleSheet:

    var styles = StyleSheet.create({ container: { borderRadius: 4, borderWidth: 0.5, @@ -17,7 +17,7 @@ easier to understand.
  • Naming the styles is a good way to add meaning to the low level components in the render function.
  • Performance:

    • Making a stylesheet from a style object makes it possible to refer to it by ID instead of creating a new style object every time.
    • It also allows to send the style only once through the bridge. All -subsequent uses are going to refer an id (not implemented yet).

    Methods #

    static create(obj: {[key: string]: any}) #

    Creates a StyleSheet style reference from the given object.

    Properties #

    hairlineWidth: CallExpression #

    This is defined as the width of a thin line on the platform. It can be +subsequent uses are going to refer an id (not implemented yet).

    Methods #

    static create(obj: {[key: string]: any}) #

    Creates a StyleSheet style reference from the given object.

    Properties #

    hairlineWidth: CallExpression #

    This is defined as the width of a thin line on the platform. It can be used as the thickness of a border or division between two elements. Example:

    { borderBottomColor: '#bbb', @@ -26,7 +26,7 @@ Example:

    flatten: CallExpression #

    © 2015 Facebook Inc.

    Switch #

    Edit on GitHub

    Universal two-state toggle component.

    Props #

    disabled bool #

    If true the user won't be able to toggle the switch. -Default value is false.

    onValueChange function #

    Invoked with the new value when the value changes.

    testID string #

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

    value bool #

    The value of the switch. If true the switch will be turned on. -Default value is false.

    iosonTintColor color #

    Background color when the switch is turned on.

    iosthumbTintColor color #

    Color of the foreground switch grip.

    iostintColor color #

    Background color when the switch is turned off.

    Examples #

    Edit on GitHub
    'use strict'; +Switch – React Native | A framework for building native apps using React

    Switch #

    Edit on GitHub

    Universal two-state toggle component.

    Props #

    disabled bool #

    If true the user won't be able to toggle the switch. +Default value is false.

    onValueChange function #

    Invoked with the new value when the value changes.

    testID string #

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

    value bool #

    The value of the switch. If true the switch will be turned on. +Default value is false.

    iosonTintColor color #

    Background color when the switch is turned on.

    iosthumbTintColor color #

    Color of the foreground switch grip.

    iostintColor color #

    Background color when the switch is turned off.

    Examples #

    Edit on GitHub
    'use strict'; var React = require('react-native'); var { @@ -141,7 +141,7 @@ Default value is false.

    < exports.title = '<Switch>'; exports.displayName = 'SwitchExample'; exports.description = 'Native boolean input'; -exports.examples = examples;

    © 2015 Facebook Inc.

    TabBarIOS.Item #

    Edit on GitHub

    Props #

    badge string, number #

    Little red bubble that sits at the top right of the icon.

    icon Image.propTypes.source #

    A custom icon for the tab. It is ignored when a system icon is defined.

    onPress function #

    Callback when this tab is being selected, you should change the state of your -component to set selected={true}.

    selected bool #

    It specifies whether the children are visible or not. If you see a -blank content, you probably forgot to add a selected one.

    selectedIcon Image.propTypes.source #

    A custom icon when the tab is selected. It is ignored when a system -icon is defined. If left empty, the icon will be tinted in blue.

    style View#style #

    React style object.

    systemIcon enum('bookmarks', 'contacts', 'downloads', 'favorites', 'featured', 'history', 'more', 'most-recent', 'most-viewed', 'recents', 'search', 'top-rated') #

    Items comes with a few predefined system icons. Note that if you are +TabBarIOS.Item – React Native | A framework for building native apps using React

    TabBarIOS.Item #

    Edit on GitHub

    Props #

    badge string, number #

    Little red bubble that sits at the top right of the icon.

    icon Image.propTypes.source #

    A custom icon for the tab. It is ignored when a system icon is defined.

    onPress function #

    Callback when this tab is being selected, you should change the state of your +component to set selected={true}.

    selected bool #

    It specifies whether the children are visible or not. If you see a +blank content, you probably forgot to add a selected one.

    selectedIcon Image.propTypes.source #

    A custom icon when the tab is selected. It is ignored when a system +icon is defined. If left empty, the icon will be tinted in blue.

    style View#style #

    React style object.

    systemIcon enum('bookmarks', 'contacts', 'downloads', 'favorites', 'featured', 'history', 'more', 'most-recent', 'most-viewed', 'recents', 'search', 'top-rated') #

    Items comes with a few predefined system icons. Note that if you are using them, the title and selectedIcon will be overridden with the -system ones.

    title string #

    Text that appears under the icon. It is ignored when a system icon -is defined.

    © 2015 Facebook Inc.

    TabBarIOS #

    Edit on GitHub

    Props #

    barTintColor color #

    Background color of the tab bar

    tintColor color #

    Color of the currently selected tab icon

    translucent bool #

    A Boolean value that indicates whether the tab bar is translucent

    Examples #

    Edit on GitHub
    'use strict'; +TabBarIOS – React Native | A framework for building native apps using React

    TabBarIOS #

    Edit on GitHub

    Props #

    barTintColor color #

    Background color of the tab bar

    tintColor color #

    Color of the currently selected tab icon

    translucent bool #

    A Boolean value that indicates whether the tab bar is translucent

    Examples #

    Edit on GitHub
    'use strict'; var React = require('react-native'); var { @@ -92,7 +92,7 @@ }, }); -module.exports = TabBarExample;
    © 2015 Facebook Inc.

    Testing #

    Edit on GitHub

    Running Tests and Contributing #

    The React Native repo has several tests you can run to verify you haven't caused a regression with your PR. These tests are run with the Travis continuous integration system, and will automatically post the results to your PR.

    We don't have perfect test coverage of course, especially for complex end-to-end interactions with the user, so many changes will still require significant manual verification, but we would love it if you want to help us increase our test coverage and add more tests and test cases!

    Jest Tests #

    Jest tests are JS-only tests run on the command line with node. The tests themselves live in the __tests__ directories of the files they test, and there is a large emphasis on aggressively mocking out functionality that is not under test for failure isolation and maximum speed. You can run the existing React Native jest tests with

    npm test

    from the react-native root, and we encourage you to add your own tests for any components you want to contribute to. See getImageSource-test.js for a basic example.

    Note: In order to run your own tests, you will have to first follow the Getting Started instructions on the Jest page and then include the jest objects below in package.json so that the scripts are pre-processed before execution.

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

    Testing #

    Edit on GitHub

    Running Tests and Contributing #

    The React Native repo has several tests you can run to verify you haven't caused a regression with your PR. These tests are run with the Travis continuous integration system, and will automatically post the results to your PR.

    We don't have perfect test coverage of course, especially for complex end-to-end interactions with the user, so many changes will still require significant manual verification, but we would love it if you want to help us increase our test coverage and add more tests and test cases!

    Jest Tests #

    Jest tests are JS-only tests run on the command line with node. The tests themselves live in the __tests__ directories of the files they test, and there is a large emphasis on aggressively mocking out functionality that is not under test for failure isolation and maximum speed. You can run the existing React Native jest tests with

    npm test

    from the react-native root, and we encourage you to add your own tests for any components you want to contribute to. See getImageSource-test.js for a basic example.

    Note: In order to run your own tests, you will have to first follow the Getting Started instructions on the Jest page and then include the jest objects below in package.json so that the scripts are pre-processed before execution.

    ... "scripts": { ... "test": "jest" @@ -19,7 +19,7 @@ "source-map" ] }, -...

    Note: you may have to install/upgrade/link Node.js and other parts of your environment in order for the tests to run correctly. Check out the latest setup in .travis.yml

    Integration Tests (iOS only) #

    React Native provides facilities to make it easier to test integrated components that require both native and JS components to communicate across the bridge. The two main components are RCTTestRunner and RCTTestModule. RCTTestRunner sets up the ReactNative environment and provides facilities to run the tests as XCTestCases in Xcode (runTest:module is the simplest method). RCTTestModule is exported to JS as NativeModules.TestModule. The tests themselves are written in JS, and must call TestModule.markTestCompleted() when they are done, otherwise the test will timeout and fail. Test failures are primarily indicated by throwing a JS exception. It is also possible to test error conditions with runTest:module:initialProps:expectErrorRegex: or runTest:module:initialProps:expectErrorBlock: which will expect an error to be thrown and verify the error matches the provided criteria. See IntegrationTestHarnessTest.js, UIExplorerIntegrationTests.m, and IntegrationTestsApp.js for example usage and integration points.

    You can run integration tests locally with cmd+U in the IntegrationTest and UIExplorer apps in Xcode.

    Snapshot Tests (iOS only) #

    A common type of integration test is the snapshot test. These tests render a component, and verify snapshots of the screen against reference images using TestModule.verifySnapshot(), using the FBSnapshotTestCase library behind the scenes. Reference images are recorded by setting recordMode = YES on the RCTTestRunner, then running the tests. Snapshots will differ slightly between 32 and 64 bit, and various OS versions, so it's recommended that you enforce tests are run with the correct configuration. It's also highly recommended that all network data be mocked out, along with other potentially troublesome dependencies. See SimpleSnapshotTest for a basic example.

    If you make a change that affects a snapshot test in a PR, such as adding a new example case to one of the examples that is snapshotted, you'll need to re-record the snapshot reference image. To do this, simply change to _runner.recordMode = YES; in UIExplorer/UIExplorerSnapshotTests.m, re-run the failing tests, then flip record back to NO and submit/update your PR and wait to see if the Travis build passes.

    © 2015 Facebook Inc.

    Text #

    Edit on GitHub

    A React component for displaying text which supports nesting, +Text – React Native | A framework for building native apps using React

    Text #

    Edit on GitHub

    A React component for displaying text which supports nesting, styling, and touch handling. In the following example, the nested title and body text will inherit the fontFamily from styles.baseText, but the title provides its own additional styles. The title and body will stack on top of @@ -23,19 +23,19 @@ each other on account of the literal newlines:

    : 20, fontWeight: 'bold', }, -};

    Props #

    accessible #

    numberOfLines number #

    Used to truncate the text with an ellipsis after computing the text +};

    Props #

    accessible #

    numberOfLines number #

    Used to truncate the text with an ellipsis after computing the text layout, including line wrapping, such that the total number of lines -does not exceed this number.

    onLayout function #

    Invoked on mount and layout changes with

    {nativeEvent: {layout: {x, y, width, height}}}

    onPress function #

    This function is called on press.

    style style #

    color color
    fontFamily string
    fontSize number
    fontStyle enum('normal', 'italic')
    fontWeight enum('normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900')

    Specifies font weight. The values 'normal' and 'bold' are supported for +does not exceed this number.

    onLayout function #

    Invoked on mount and layout changes with

    {nativeEvent: {layout: {x, y, width, height}}}

    onPress function #

    This function is called on press.

    style style #

    color color
    fontFamily string
    fontSize number
    fontStyle enum('normal', 'italic')
    fontWeight enum('normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900')

    Specifies font weight. The values 'normal' and 'bold' are supported for most fonts. Not all fonts have a variant for each of the numeric values, -in that case the closest one is chosen.

    lineHeight number
    textAlign enum('auto', 'left', 'right', 'center', 'justify')

    Specifies text alignment. The value 'justify' is only supported on iOS.

    textShadowColor color
    textShadowOffset {width: number, height: number}
    textShadowRadius number
    androidtextAlignVertical enum('auto', 'top', 'bottom', 'center')
    iosletterSpacing number
    iostextDecorationColor color
    iostextDecorationLine enum('none', 'underline', 'line-through', 'underline line-through')
    iostextDecorationStyle enum('solid', 'double', 'dotted', 'dashed')
    ioswritingDirection enum('auto', 'ltr', 'rtl')

    testID string #

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

    iosallowFontScaling bool #

    Specifies should fonts scale to respect Text Size accessibility setting on iOS.

    iossuppressHighlighting bool #

    When true, no visual change is made when text is pressed down. By -default, a gray oval highlights the text on press down.

    Description #

    Edit on GitHub

    Nested Text #

    In iOS, the way to display formatted text is by using NSAttributedString: you give the text that you want to display and annotate ranges with some specific formatting. In practice, this is very tedious. For React Native, we decided to use web paradigm for this where you can nest text to achieve the same effect.

    <Text style={{fontWeight: 'bold'}}> +in that case the closest one is chosen.

    lineHeight number
    textAlign enum('auto', 'left', 'right', 'center', 'justify')

    Specifies text alignment. The value 'justify' is only supported on iOS.

    textShadowColor color
    textShadowOffset {width: number, height: number}
    textShadowRadius number
    androidtextAlignVertical enum('auto', 'top', 'bottom', 'center')
    iosletterSpacing number
    iostextDecorationColor color
    iostextDecorationLine enum('none', 'underline', 'line-through', 'underline line-through')
    iostextDecorationStyle enum('solid', 'double', 'dotted', 'dashed')
    ioswritingDirection enum('auto', 'ltr', 'rtl')

    testID string #

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

    iosallowFontScaling bool #

    Specifies should fonts scale to respect Text Size accessibility setting on iOS.

    iossuppressHighlighting bool #

    When true, no visual change is made when text is pressed down. By +default, a gray oval highlights the text on press down.

    Description #

    Edit on GitHub

    Nested Text #

    In iOS, the way to display formatted text is by using NSAttributedString: you give the text that you want to display and annotate ranges with some specific formatting. In practice, this is very tedious. For React Native, we decided to use web paradigm for this where you can nest text to achieve the same effect.

    <Text style={{fontWeight: 'bold'}}> I am bold <Text style={{color: 'red'}}> and red </Text> </Text>

    Behind the scenes, this is going to be converted to a flat NSAttributedString that contains the following information

    "I am bold and red" 0-9: bold -9-17: bold, red

    Containers #

    The <Text> element is special relative to layout: everything inside is no longer using the flexbox layout but using text layout. This means that elements inside of a <Text> are no longer rectangles, but wrap when they see the end of the line.

    <Text> +9-17: bold, red

    Containers #

    The <Text> element is special relative to layout: everything inside is no longer using the flexbox layout but using text layout. This means that elements inside of a <Text> are no longer rectangles, but wrap when they see the end of the line.

    <Text> <Text>First part and </Text> <Text>second part</Text> </Text> @@ -51,7 +51,7 @@ default, a gray oval highlights the text on press down.

    // |First part | // |and | -// |second part|

    Limited Style Inheritance #

    On the web, the usual way to set a font family and size for the entire document is to write:

    /* CSS, *not* React Native */ +// |second part|

    Limited Style Inheritance #

    On the web, the usual way to set a font family and size for the entire document is to write:

    /* CSS, *not* React Native */ html { font-family: 'lucida grande', tahoma, verdana, arial, sans-serif; font-size: 11px; @@ -74,7 +74,7 @@ html { <Text style={{color: 'red'}}> and red </Text> -</Text>

    We believe that this more constrained way to style text will yield better apps:

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

    • (Implementor) The implementation of React Native is also simplified. We do not need to have a fontFamily field on every single element, and we do not need to potentially traverse the tree up to the root every time we display a text node. The style inheritance is only encoded inside of the native Text component and doesn't leak to other components or the system itself.

    © 2015 Facebook Inc.

    TextInput #

    Edit on GitHub

    A foundational component for inputting text into the app via a +TextInput – React Native | A framework for building native apps using React

    TextInput #

    Edit on GitHub

    A foundational component for inputting text into the app via a keyboard. Props provide configurability for several features, such as auto-correction, auto-capitalization, placeholder text, and different keyboard types, such as a numeric keypad.

    The simplest use case is to plop down a TextInput and subscribe to the @@ -8,33 +8,33 @@ example:

    <TextInput style={{height: 40, borderColor: 'gray', borderWidth: 1}} onChangeText={(text) => this.setState({text})} value={this.state.text} - />

    Note that some props are only available with multiline={true/false}:

    Props #

    autoCapitalize enum('none', 'sentences', 'words', 'characters') #

    Can tell TextInput to automatically capitalize certain characters.

    • characters: all characters,
    • words: first letter of each word
    • sentences: first letter of each sentence (default)
    • none: don't auto capitalize anything

    autoCorrect bool #

    If false, disables auto-correct. The default value is true.

    autoFocus bool #

    If true, focuses the input on componentDidMount. -The default value is false.

    defaultValue string #

    Provides an initial value that will change when the user starts typing. + />

    Note that some props are only available with multiline={true/false}:

    Props #

    autoCapitalize enum('none', 'sentences', 'words', 'characters') #

    Can tell TextInput to automatically capitalize certain characters.

    • characters: all characters,
    • words: first letter of each word
    • sentences: first letter of each sentence (default)
    • none: don't auto capitalize anything

    autoCorrect bool #

    If false, disables auto-correct. The default value is true.

    autoFocus bool #

    If true, focuses the input on componentDidMount. +The default value is false.

    defaultValue string #

    Provides an initial value that will change when the user starts typing. Useful for simple use-cases where you don't want to deal with listening -to events and updating the value prop to keep the controlled state in sync.

    editable bool #

    If false, text is not editable. The default value is true.

    keyboardType enum('default', 'email-address', 'numeric', 'phone-pad', 'ascii-capable', 'numbers-and-punctuation', 'url', 'number-pad', 'name-phone-pad', 'decimal-pad', 'twitter', 'web-search') #

    Determines which keyboard to open, e.g.numeric.

    The following values work across platforms: +to events and updating the value prop to keep the controlled state in sync.

    editable bool #

    If false, text is not editable. The default value is true.

    keyboardType enum('default', 'email-address', 'numeric', 'phone-pad', 'ascii-capable', 'numbers-and-punctuation', 'url', 'number-pad', 'name-phone-pad', 'decimal-pad', 'twitter', 'web-search') #

    Determines which keyboard to open, e.g.numeric.

    The following values work across platforms: - default - numeric -- email-address

    maxLength number #

    Limits the maximum number of characters that can be entered. Use this -instead of implementing the logic in JS to avoid flicker.

    multiline bool #

    If true, the text input can be multiple lines. -The default value is false.

    onBlur function #

    Callback that is called when the text input is blurred

    onChange function #

    Callback that is called when the text input's text changes.

    onChangeText function #

    Callback that is called when the text input's text changes. -Changed text is passed as an argument to the callback handler.

    onEndEditing function #

    Callback that is called when text input ends.

    onFocus function #

    Callback that is called when the text input is focused

    onLayout function #

    Invoked on mount and layout changes with {x, y, width, height}.

    onSelectionChange function #

    Callback that is called when the text input selection is changed

    onSubmitEditing function #

    Callback that is called when the text input's submit button is pressed. -Invalid if multiline={true} is specified.

    placeholder string #

    The string that will be rendered before text input has been entered

    placeholderTextColor string #

    The text color of the placeholder string

    secureTextEntry bool #

    If true, the text input obscures the text entered so that sensitive text -like passwords stay secure. The default value is false.

    selectionColor string #

    The highlight (and cursor on ios) color of the text input

    style Text#style #

    Styles

    value string #

    The value to show for the text input. TextInput is a controlled +- email-address

    maxLength number #

    Limits the maximum number of characters that can be entered. Use this +instead of implementing the logic in JS to avoid flicker.

    multiline bool #

    If true, the text input can be multiple lines. +The default value is false.

    onBlur function #

    Callback that is called when the text input is blurred

    onChange function #

    Callback that is called when the text input's text changes.

    onChangeText function #

    Callback that is called when the text input's text changes. +Changed text is passed as an argument to the callback handler.

    onEndEditing function #

    Callback that is called when text input ends.

    onFocus function #

    Callback that is called when the text input is focused

    onLayout function #

    Invoked on mount and layout changes with {x, y, width, height}.

    onSelectionChange function #

    Callback that is called when the text input selection is changed

    onSubmitEditing function #

    Callback that is called when the text input's submit button is pressed. +Invalid if multiline={true} is specified.

    placeholder string #

    The string that will be rendered before text input has been entered

    placeholderTextColor string #

    The text color of the placeholder string

    secureTextEntry bool #

    If true, the text input obscures the text entered so that sensitive text +like passwords stay secure. The default value is false.

    selectionColor string #

    The highlight (and cursor on ios) color of the text input

    style Text#style #

    Styles

    value string #

    The value to show for the text input. TextInput is a controlled component, which means the native value will be forced to match this value prop if provided. For most uses this works great, but in some cases this may cause flickering - one common cause is preventing edits by keeping value the same. In addition to simply setting the same value, either set editable={false}, or set/update maxLength to prevent -unwanted edits without flicker.

    androidnumberOfLines number #

    Sets the number of lines for a TextInput. Use it with multiline set to -true to be able to fill the lines.

    androidunderlineColorAndroid string #

    The color of the textInput underline.

    iosblurOnSubmit bool #

    If true, the text field will blur when submitted. +unwanted edits without flicker.

    androidnumberOfLines number #

    Sets the number of lines for a TextInput. Use it with multiline set to +true to be able to fill the lines.

    androidunderlineColorAndroid string #

    The color of the textInput underline.

    iosblurOnSubmit bool #

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

    iosclearButtonMode enum('never', 'while-editing', 'unless-editing', 'always') #

    When the clear button should appear on the right side of the text view

    iosclearTextOnFocus bool #

    If true, clears the text field automatically when editing begins

    iosenablesReturnKeyAutomatically bool #

    If true, the keyboard disables the return key when there is no text and -automatically enables it when there is text. The default value is false.

    ioskeyboardAppearance enum('default', 'light', 'dark') #

    Determines the color of the keyboard.

    iosonKeyPress function #

    Callback that is called when a key is pressed. +onSubmitEditing event instead of inserting a newline into the field.

    iosclearButtonMode enum('never', 'while-editing', 'unless-editing', 'always') #

    When the clear button should appear on the right side of the text view

    iosclearTextOnFocus bool #

    If true, clears the text field automatically when editing begins

    iosenablesReturnKeyAutomatically bool #

    If true, the keyboard disables the return key when there is no text and +automatically enables it when there is text. The default value is false.

    ioskeyboardAppearance enum('default', 'light', 'dark') #

    Determines the color of the keyboard.

    iosonKeyPress function #

    Callback that is called when a key is pressed. Pressed key value is passed as an argument to the callback handler. -Fires before onChange callbacks.

    iosreturnKeyType enum('default', 'go', 'google', 'join', 'next', 'route', 'search', 'send', 'yahoo', 'done', 'emergency-call') #

    Determines how the return key should look.

    iosselectTextOnFocus bool #

    If true, all text will automatically be selected on focus

    iosselectionState DocumentSelectionState #

    See DocumentSelectionState.js, some state that is responsible for -maintaining selection information for a document

    © 2015 Facebook Inc.

    TimePickerAndroid #

    Edit on GitHub

    Opens the standard Android time picker dialog.

    Example #

    try { + const {action, hour, minute} = await TimePickerAndroid.open({ + hour: 14, + minute: 0, + is24Hour: false, // Will display '2 PM' + }); + if (action !== DatePickerAndroid.dismissedAction) { + // Selected hour (0-23), minute (0-59) + } +} catch ({code, message}) { + console.warn('Cannot open time picker', message); +}

    Methods #

    static open(options: Object) #

    Opens the standard Android time picker dialog.

    The available keys for the options object are: + hour (0-23) - the hour to show, defaults to the current time + minute (0-59) - the minute to show, defaults to the current time + * is24Hour (boolean) - If true, the picker uses the 24-hour format. If false, + the picker shows an AM/PM chooser. If undefined, the default for the current locale + is used.

    Returns a Promise which will be invoked an object containing action, hour (0-23), +minute (0-59) if the user picked a time. If the user dismissed the dialog, the Promise will +still be resolved with action being TimePickerAndroid.dismissedAction and all the other keys +being undefined. Always check whether the action before reading the values.

    static timeSetAction() #

    A time has been selected.

    static dismissedAction() #

    The dialog has been dismissed.

    Examples #

    Edit on GitHub
    'use strict'; + +var React = require('react-native'); +var { + TimePickerAndroid, + StyleSheet, + Text, + TouchableWithoutFeedback, +} = React; + +var UIExplorerBlock = require('./UIExplorerBlock'); +var UIExplorerPage = require('./UIExplorerPage'); + +var TimePickerAndroidExample = React.createClass({ + + statics: { + title: 'TimePickerAndroid', + description: 'Standard Android time picker dialog', + }, + + getInitialState() { + // *Text, *Hour and *Minute are set by successCallback -- this updates the text with the time + // picked by the user and makes it so the next time they open it the hour and minute they picked + // before is displayed. + return { + isoFormatText: 'pick a time (24-hour format)', + presetHour: 4, + presetMinute: 4, + presetText: 'pick a time, default: 4:04AM', + simpleText: 'pick a time', + }; + }, + + async showPicker(stateKey, options) { + try { + const {action, minute, hour} = await TimePickerAndroid.open(options); + var newState = {}; + if (action === TimePickerAndroid.timeSetAction) { + newState[stateKey + 'Text'] = _formatTime(hour, minute); + newState[stateKey + 'Hour'] = hour; + newState[stateKey + 'Minute'] = minute; + } else if (action === TimePickerAndroid.dismissedAction) { + newState[stateKey + 'Text'] = 'dismissed'; + } + this.setState(newState); + } catch ({code, message}) { + console.warn(`Error in example '${stateKey}': `, message); + } + }, + + render() { + return ( + <UIExplorerPage title="TimePickerAndroid"> + <UIExplorerBlock title="Simple time picker"> + <TouchableWithoutFeedback + onPress={this.showPicker.bind(this, 'simple')}> + <Text style={styles.text}>{this.state.simpleText}</Text> + </TouchableWithoutFeedback> + </UIExplorerBlock> + <UIExplorerBlock title="Time picker with pre-set time"> + <TouchableWithoutFeedback + onPress={this.showPicker.bind(this, 'preset', { + hour: this.state.presetHour, + minute: this.state.presetMinute, + })}> + <Text style={styles.text}>{this.state.presetText}</Text> + </TouchableWithoutFeedback> + </UIExplorerBlock> + + <UIExplorerBlock title="Time picker with 24-hour time format"> + <TouchableWithoutFeedback + onPress={this.showPicker.bind(this, 'isoFormat', { + hour: this.state.isoFormatHour, + minute: this.state.isoFormatMinute, + is24Hour: true, + })}> + <Text style={styles.text}>{this.state.isoFormatText}</Text> + </TouchableWithoutFeedback> + </UIExplorerBlock> + </UIExplorerPage> + ); + }, +}); + +/** + * Returns e.g. '3:05'. + */ +function _formatTime(hour, minute) { + return hour + ':' + (minute < 10 ? '0' + minute : minute); +} + +var styles = StyleSheet.create({ + text: { + color: 'black', + }, +}); + +module.exports = TimePickerAndroidExample;
    © 2016 Facebook Inc.
    \ No newline at end of file diff --git a/docs/timers.html b/docs/timers.html index 2de7ebc7f01..dda7985e9c9 100644 --- a/docs/timers.html +++ b/docs/timers.html @@ -1,10 +1,10 @@ -Timers – React Native | A framework for building native apps using React

    Timers #

    Edit on GitHub

    Timers are an important part of an application and React Native implements the browser timers.

    Timers #

    • setTimeout, clearTimeout
    • setInterval, clearInterval
    • setImmediate, clearImmediate
    • requestAnimationFrame, cancelAnimationFrame

    requestAnimationFrame(fn) is not the same as setTimeout(fn, 0) - the former will fire after all the frame has flushed, whereas the latter will fire as quickly as possible (over 1000x per second on a iPhone 5S).

    setImmediate is executed at the end of the current JavaScript execution block, right before sending the batched response back to native. Note that if you call setImmediate within a setImmediate callback, it will be executed right away, it won't yield back to native in between.

    The Promise implementation uses setImmediate as its asynchronicity primitive.

    InteractionManager #

    One reason why well-built native apps feel so smooth is by avoiding expensive operations during interactions and animations. In React Native, we currently have a limitation that there is only a single JS execution thread, but you can use InteractionManager to make sure long-running work is scheduled to start after any interactions/animations have completed.

    Applications can schedule tasks to run after interactions with the following:

    InteractionManager.runAfterInteractions(() => { +Timers – React Native | A framework for building native apps using React

    Timers #

    Edit on GitHub

    Timers are an important part of an application and React Native implements the browser timers.

    Timers #

    • setTimeout, clearTimeout
    • setInterval, clearInterval
    • setImmediate, clearImmediate
    • requestAnimationFrame, cancelAnimationFrame

    requestAnimationFrame(fn) is not the same as setTimeout(fn, 0) - the former will fire after all the frame has flushed, whereas the latter will fire as quickly as possible (over 1000x per second on a iPhone 5S).

    setImmediate is executed at the end of the current JavaScript execution block, right before sending the batched response back to native. Note that if you call setImmediate within a setImmediate callback, it will be executed right away, it won't yield back to native in between.

    The Promise implementation uses setImmediate as its asynchronicity primitive.

    InteractionManager #

    One reason why well-built native apps feel so smooth is by avoiding expensive operations during interactions and animations. In React Native, we currently have a limitation that there is only a single JS execution thread, but you can use InteractionManager to make sure long-running work is scheduled to start after any interactions/animations have completed.

    Applications can schedule tasks to run after interactions with the following:

    InteractionManager.runAfterInteractions(() => { // ...long-running synchronous task... });

    Compare this to other scheduling alternatives:

    • requestAnimationFrame(): for code that animates a view over time.
    • setImmediate/setTimeout/setInterval(): run code later, note this may delay animations.
    • runAfterInteractions(): run code later, without delaying active animations.

    The touch handling system considers one or more active touches to be an 'interaction' and will delay runAfterInteractions() callbacks until all touches have ended or been cancelled.

    InteractionManager also allows applications to register animations by creating an interaction 'handle' on animation start, and clearing it upon completion:

    var handle = InteractionManager.createInteractionHandle(); // run animation... (`runAfterInteractions` tasks are queued) // later, on animation completion: InteractionManager.clearInteractionHandle(handle); -// queued tasks run if all handles were cleared

    TimerMixin #

    We found out that the primary cause of fatals in apps created with React Native was due to timers firing after a component was unmounted. To solve this recurring issue, we introduced TimerMixin. If you include TimerMixin, then you can replace your calls to setTimeout(fn, 500) with this.setTimeout(fn, 500) (just prepend this.) and everything will be properly cleaned up for you when the component unmounts.

    This library does not ship with React Native - in order to use it on your project, you will need to install it with npm i react-timer-mixin --save from your project directory.

    var TimerMixin = require('react-timer-mixin'); +// queued tasks run if all handles were cleared

    TimerMixin #

    We found out that the primary cause of fatals in apps created with React Native was due to timers firing after a component was unmounted. To solve this recurring issue, we introduced TimerMixin. If you include TimerMixin, then you can replace your calls to setTimeout(fn, 500) with this.setTimeout(fn, 500) (just prepend this.) and everything will be properly cleaned up for you when the component unmounts.

    This library does not ship with React Native - in order to use it on your project, you will need to install it with npm i react-timer-mixin --save from your project directory.

    import TimerMixin from 'react-timer-mixin'; var Component = React.createClass({ mixins: [TimerMixin], @@ -14,7 +14,7 @@ 500 ); } -});

    We strongly discourage using the global setTimeout(...) and recommend instead that you use this.setTimeout(...) provided by react-timer-mixin. This will eliminate a lot of hard work tracking down bugs, such as crashes caused by timeouts firing after a component has been unmounted.

    © 2015 Facebook Inc.

    ToastAndroid #

    Edit on GitHub

    This exposes the native ToastAndroid module as a JS module. This has a function 'show' -which takes the following parameters:

    1. String message: A string with the text to toast
    2. int duration: The duration of the toast. May be ToastAndroid.SHORT or ToastAndroid.LONG

    Methods #

    static show(message: string, duration: number) #

    Properties #

    SHORT: MemberExpression #

    LONG: MemberExpression #

    Examples #

    Edit on GitHub
    'use strict'; +ToastAndroid – React Native | A framework for building native apps using React

    ToastAndroid #

    Edit on GitHub

    This exposes the native ToastAndroid module as a JS module. This has a function 'show' +which takes the following parameters:

    1. String message: A string with the text to toast
    2. int duration: The duration of the toast. May be ToastAndroid.SHORT or ToastAndroid.LONG

    Methods #

    static show(message: string, duration: number) #

    Properties #

    SHORT: MemberExpression #

    LONG: MemberExpression #

    Examples #

    Edit on GitHub
    'use strict'; var React = require('react-native'); var { @@ -51,7 +51,7 @@ which takes the following parameters:

    1. String message: A string with t }, }); -module.exports = ToastExample;
    © 2015 Facebook Inc.

    ToolbarAndroid #

    Edit on GitHub

    React component that wraps the Android-only Toolbar widget. A Toolbar can display a logo, +ToolbarAndroid – React Native | A framework for building native apps using React

    ToolbarAndroid #

    Edit on GitHub

    React component that wraps the Android-only Toolbar widget. A Toolbar can display a logo, navigation icon (e.g. hamburger menu), a title & subtitle and a list of actions. The title and subtitle are expanded so the logo and navigation icons are displayed on the left, title and subtitle in the middle and the actions on the right.

    If the toolbar has an only child, it will be displayed between the title and actions.

    Although the Toolbar supports remote images for the logo, navigation and action icons, this @@ -18,20 +18,20 @@ onActionSelected: if (position === 0) { // index of 'Settings' showSettings(); } -}

    Props #

    actions [{title: string, icon: optionalImageSource, show: enum('always', 'ifRoom', 'never'), showWithText: bool}] #

    Sets possible actions on the toolbar as part of the action menu. These are displayed as icons +}

    Props #

    actions [{title: string, icon: optionalImageSource, show: enum('always', 'ifRoom', 'never'), showWithText: bool}] #

    Sets possible actions on the toolbar as part of the action menu. These are displayed as icons or text on the right side of the widget. If they don't fit they are placed in an 'overflow' menu.

    This property takes an array of objects, where each object has the following keys:

    • title: required, the title of this action
    • icon: the icon for this action, e.g. require('./some_icon.png')
    • show: when to show this action as an icon or hide it in the overflow menu: always, -ifRoom or never
    • showWithText: boolean, whether to show text alongside the icon or not

    contentInsetEnd number #

    Sets the content inset for the toolbar ending edge.

    The content inset affects the valid area for Toolbar content other than +ifRoom or never

  • showWithText: boolean, whether to show text alongside the icon or not
  • contentInsetEnd number #

    Sets the content inset for the toolbar ending edge.

    The content inset affects the valid area for Toolbar content other than the navigation button and menu. Insets define the minimum margin for these components and can be used to effectively align Toolbar content -along well-known gridlines.

    contentInsetStart number #

    Sets the content inset for the toolbar starting edge.

    The content inset affects the valid area for Toolbar content other than +along well-known gridlines.

    contentInsetStart number #

    Sets the content inset for the toolbar starting edge.

    The content inset affects the valid area for Toolbar content other than the navigation button and menu. Insets define the minimum margin for these components and can be used to effectively align Toolbar content -along well-known gridlines.

    logo optionalImageSource #

    Sets the toolbar logo.

    navIcon optionalImageSource #

    Sets the navigation icon.

    onActionSelected function #

    Callback that is called when an action is selected. The only argument that is passed to the -callback is the position of the action in the actions array.

    onIconClicked function #

    Callback called when the icon is selected.

    overflowIcon optionalImageSource #

    Sets the overflow icon.

    rtl bool #

    Used to set the toolbar direction to RTL. +along well-known gridlines.

    logo optionalImageSource #

    Sets the toolbar logo.

    navIcon optionalImageSource #

    Sets the navigation icon.

    onActionSelected function #

    Callback that is called when an action is selected. The only argument that is passed to the +callback is the position of the action in the actions array.

    onIconClicked function #

    Callback called when the icon is selected.

    overflowIcon optionalImageSource #

    Sets the overflow icon.

    rtl bool #

    Used to set the toolbar direction to RTL. In addition to this property you need to add

    android:supportsRtl="true"

    to your application AndroidManifest.xml and then call setLayoutDirection(LayoutDirection.RTL) in your MainActivity -onCreate method.

    subtitle string #

    Sets the toolbar subtitle.

    subtitleColor color #

    Sets the toolbar subtitle color.

    testID string #

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

    title string #

    Sets the toolbar title.

    titleColor color #

    Sets the toolbar title color.

    Examples #

    Edit on GitHub
    'use strict'; +onCreate method.

    subtitle string #

    Sets the toolbar subtitle.

    subtitleColor color #

    Sets the toolbar subtitle color.

    testID string #

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

    title string #

    Sets the toolbar title.

    titleColor color #

    Sets the toolbar title color.

    Examples #

    Edit on GitHub
    'use strict'; var React = require('react-native'); var { @@ -148,7 +148,7 @@ In addition to this property you need to add

    android:supportsRtl="t }, }); -module.exports = ToolbarAndroidExample;

    © 2015 Facebook Inc.

    TouchableHighlight #

    Edit on GitHub

    A wrapper for making views respond properly to touches. +TouchableHighlight – React Native | A framework for building native apps using React

    TouchableHighlight #

    Edit on GitHub

    A wrapper for making views respond properly to touches. On press down, the opacity of the wrapped view is decreased, which allows the underlay color to show through, darkening or tinting the view. The underlay comes from adding a view to the view hierarchy, which can sometimes @@ -12,9 +12,9 @@ backgroundColor of the wrapped view isn't explicitly set to an opaque color /> </TouchableHighlight> ); -},

    NOTE: TouchableHighlight supports only one child

    If you wish to have several child components, wrap them in a View.

    Props #

    activeOpacity number #

    Determines what the opacity of the wrapped view should be when touch is -active.

    onHideUnderlay function #

    Called immediately after the underlay is hidden

    onShowUnderlay function #

    Called immediately after the underlay is shown

    underlayColor color #

    The color of the underlay that will show through when the touch is -active.

    © 2015 Facebook Inc.

    TouchableNativeFeedback #

    Edit on GitHub

    A wrapper for making views respond properly to touches (Android only). +TouchableNativeFeedback – React Native | A framework for building native apps using React

    TouchableNativeFeedback #

    Edit on GitHub

    A wrapper for making views respond properly to touches (Android only). On Android this component uses native state drawable to display touch feedback. At the moment it only supports having a single View instance as a child node, as it's implemented by replacing that View with another instance @@ -13,7 +13,7 @@ of RCTView node with some additional properties set.

    Background drawable o </View> </TouchableNativeFeedback> ); -},

    Props #

    background backgroundPropType #

    Determines the type of background drawable that's going to be used to +},

    Props #

    background backgroundPropType #

    Determines the type of background drawable that's going to be used to display feedback. It takes an object with type property and extra data depending on the type. It's recommended to use one of the following static methods to generate that dictionary:

    1) TouchableNativeFeedback.SelectableBackground() - will create object @@ -26,7 +26,7 @@ object that represents ripple drawable with specified color (as a string). If property borderless evaluates to true the ripple will render outside of the view bounds (see native actionbar buttons as an example of that behavior). This background type is available on Android -API level 21+

    © 2015 Facebook Inc.

    TouchableOpacity #

    Edit on GitHub

    A wrapper for making views respond properly to touches. +TouchableOpacity – React Native | A framework for building native apps using React

    TouchableOpacity #

    Edit on GitHub

    A wrapper for making views respond properly to touches. On press down, the opacity of the wrapped view is decreased, dimming it. This is done without actually changing the view hierarchy, and in general is easy to add to an app without weird side-effects.

    Example:

    renderButton: function() { @@ -10,8 +10,8 @@ easy to add to an app without weird side-effects.

    Example:

    /> </TouchableOpacity> ); -},

    Props #

    activeOpacity number #

    Determines what the opacity of the wrapped view should be when touch is -active.

    © 2015 Facebook Inc.

    TouchableWithoutFeedback #

    Edit on GitHub

    Do not use unless you have a very good reason. All the elements that +TouchableWithoutFeedback – React Native | A framework for building native apps using React

    TouchableWithoutFeedback #

    Edit on GitHub

    Do not use unless you have a very good reason. All the elements that respond to press should have a visual feedback when touched. This is -one of the primary reason a "web" app doesn't feel "native".

    NOTE: TouchableWithoutFeedback supports only one child

    If you wish to have several child components, wrap them in a View.

    Props #

    accessibilityComponentType View.AccessibilityComponentType #

    accessibilityTraits View.AccessibilityTraits, [View.AccessibilityTraits] #

    accessible bool #

    delayLongPress number #

    Delay in ms, from onPressIn, before onLongPress is called.

    delayPressIn number #

    Delay in ms, from the start of the touch, before onPressIn is called.

    delayPressOut number #

    Delay in ms, from the release of the touch, before onPressOut is called.

    onLayout function #

    Invoked on mount and layout changes with

    {nativeEvent: {layout: {x, y, width, height}}}

    onLongPress function #

    onPress function #

    Called when the touch is released, but not if cancelled (e.g. by a scroll -that steals the responder lock).

    onPressIn function #

    onPressOut function #

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

    When the scroll view is disabled, this defines how far your touch may +one of the primary reason a "web" app doesn't feel "native".

    NOTE: TouchableWithoutFeedback supports only one child

    If you wish to have several child components, wrap them in a View.

    Props #

    accessibilityComponentType View.AccessibilityComponentType #

    accessibilityTraits View.AccessibilityTraits, [View.AccessibilityTraits] #

    accessible bool #

    delayLongPress number #

    Delay in ms, from onPressIn, before onLongPress is called.

    delayPressIn number #

    Delay in ms, from the start of the touch, before onPressIn is called.

    delayPressOut number #

    Delay in ms, from the release of the touch, before onPressOut is called.

    onLayout function #

    Invoked on mount and layout changes with

    {nativeEvent: {layout: {x, y, width, height}}}

    onLongPress function #

    onPress function #

    Called when the touch is released, but not if cancelled (e.g. by a scroll +that steals the responder lock).

    onPressIn function #

    onPressOut function #

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

    When the scroll view is disabled, this defines how far your touch may move off of the button, before deactivating the button. Once deactivated, try moving it back and you'll see that the button is once again reactivated! Move it back and forth several times while the scroll view -is disabled. Ensure you pass in a constant to reduce memory allocations.

    © 2015 Facebook Inc.

    Transforms #

    Edit on GitHub

    Props #

    transform [{perspective: number}, {rotate: string}, {rotateX: string}, {rotateY: string}, {rotateZ: string}, {scale: number}, {scaleX: number}, {scaleY: number}, {translateX: number}, {translateY: number}, {skewX: string}, {skewY: string}] #

    transformMatrix TransformMatrixPropType #

    © 2015 Facebook Inc.

    Transforms #

    Edit on GitHub

    Props #

    transform [{perspective: number}, {rotate: string}, {rotateX: string}, {rotateY: string}, {rotateZ: string}, {scale: number}, {scaleX: number}, {scaleY: number}, {translateX: number}, {translateY: number}, {skewX: string}, {skewY: string}] #

    transformMatrix TransformMatrixPropType #

    © 2016 Facebook Inc.

    Troubleshooting #

    Edit on GitHub

    Cmd-R does not reload the simulator #

    Enable iOS simulator's "Connect hardware keyboard" from menu Hardware > Keyboard menu.

    Keyboard Menu

    If you are using a non-QWERTY/AZERTY keyboard layout you can use the Hardware > Shake Gesture to bring up the dev menu and click "Refresh"

    Port already in use red-screen #

    red-screen

    Something is probably already running on port 8081. You can either kill it or try to change which port the packager is listening to.

    Kill process on port 8081 #

    $ sudo lsof -n -i4TCP:8081 | grep LISTEN

    then

    $ kill -9 <cma process id>

    Change the port in Xcode #

    Edit AppDelegate.m to use a different port.

    // OPTION 1 +Troubleshooting – React Native | A framework for building native apps using React

    Troubleshooting #

    Edit on GitHub

    Cmd-R does not reload the simulator #

    Enable iOS simulator's "Connect hardware keyboard" from menu Hardware > Keyboard menu.

    Keyboard Menu

    If you are using a non-QWERTY/AZERTY keyboard layout you can use the Hardware > Shake Gesture to bring up the dev menu and click "Refresh"

    Port already in use red-screen #

    red-screen

    Something is probably already running on port 8081. You can either kill it or try to change which port the packager is listening to.

    Kill process on port 8081 #

    $ sudo lsof -n -i4TCP:8081 | grep LISTEN

    then

    $ kill -9 <cma process id>

    Change the port in Xcode #

    Edit AppDelegate.m to use a different port.

    // OPTION 1 // Load from development server. Start the server from the repository root: // // $ npm start // // To run on device, change `localhost` to the IP address of your computer, and make sure your computer and // iOS device are on the same Wi-Fi network. - jsCodeLocation = [NSURL URLWithString:@"http://localhost:9381/index.ios.bundle"];

    Watchman took too long to load #

    Permission settings prevent Watchman from loading. A recent update solves this, get a HEAD install of Watchman if you are experiencing this error.

    brew uninstall watchman -brew install --HEAD watchman

    NPM locking error #

    If in the react-native init <project> phase you saw npm fail with "npm WARN locking Error: EACCES" then try the following:

    sudo chown -R $USER ~/.npm -sudo chown -R $USER /usr/local/lib/node_modules

    Debugging in Chrome hangs and/or does not work well #

    It is possible that one of your Chrome extensions is interacting in unexpected ways with the debugger. If you are having this issue, try disabling all of your extensions and re-enabling them one-by-one until you find the problematic extension.

    Xcode Build Failures #

    To see the exact error that is causing your build to fail, go into the Issues Navigator in the left sidebar.

    React libraries missing #

    If you are using CocoaPods, verify that you have added React along with the subspecs to the Podfile. For example, if you were using the <Text />, <Image /> and fetch() APIs, you would need to add these in your Podfile:

    pod 'React', :path => '../node_modules/react-native', :subspecs => [ + jsCodeLocation = [NSURL URLWithString:@"http://localhost:9381/index.ios.bundle"];

    Watchman took too long to load #

    Permission settings prevent Watchman from loading. A recent update solves this, get a HEAD install of Watchman if you are experiencing this error.

    brew uninstall watchman +brew install --HEAD watchman

    NPM locking error #

    If in the react-native init <project> phase you saw npm fail with "npm WARN locking Error: EACCES" then try the following:

    sudo chown -R $USER ~/.npm +sudo chown -R $USER /usr/local/lib/node_modules

    Debugging in Chrome hangs and/or does not work well #

    It is possible that one of your Chrome extensions is interacting in unexpected ways with the debugger. If you are having this issue, try disabling all of your extensions and re-enabling them one-by-one until you find the problematic extension.

    Xcode Build Failures #

    To see the exact error that is causing your build to fail, go into the Issues Navigator in the left sidebar.

    React libraries missing #

    If you are using CocoaPods, verify that you have added React along with the subspecs to the Podfile. For example, if you were using the <Text />, <Image /> and fetch() APIs, you would need to add these in your Podfile:

    pod 'React', :path => '../node_modules/react-native', :subspecs => [ 'RCTText', 'RCTImage', 'RCTNetwork', 'RCTWebSocket', -]

    Next, make sure you have run pod install and that a Pods/ directory has been created in your project with React installed. CocoaPods will instruct you to use the generated .xcworkspace file henceforth to be able to use these installed dependencies.

    If you are adding React manually, make sure you have included all the relevant dependencies, like RCTText.xcodeproj, RCTImage.xcodeproj depending on the ones you are using. Next, the binaries built by these dependencies have to be linked to your app binary. Use the Linked Frameworks and Binaries section in the Xcode project settings. More detailed steps are here: Linking Libraries.

    Argument list too long: recursive header expansion failed #

    In the project's build settings, User Search Header Paths and Header Search Paths are two configs that specify where Xcode should look for #import header files specified in the code. For Pods, CocoaPods uses a default array of specific folders to look in. Verify that this particular config is not overwritten, and that none of the folders configured are too large. If one of the folders is a large folder, Xcode will attempt to recursively search the entire directory and throw above error at some point.

    To revert the User Search Header Paths and Header Search Paths build settings to their defaults set by CocoaPods - select the entry in the Build Settings panel, and hit delete. It will remove the custom override and return to the CocoaPod defaults.

    Unable to connect to development server #

    iOS #

    Ensure that you are on the same WiFi network as your computer. If you're using a cell data plan, your phone can't access your computer's local IP address.

    Android #

    You need to run adb reverse tcp:8081 tcp:8081 to forward requests from the device to your computer. This works only on Android 5.0 and newer.

    Module that uses WebSocket (such as Firebase) throws an exception #

    React Native implements a polyfill for WebSockets. These polyfills are initialized as part of the react-native module that you include in your application through require('react-native'). If you load another module that requires WebSockets, be sure to load/require it after react-native.

    So:

    var React = require('react-native'); -var Firebase = require('firebase');

    Requiring firebase before react-native will result in a 'No transports available' redbox.

    Discovered thanks to issue #3645. If you're curious, the polyfills are set up in InitializeJavaScriptAppEngine.js.

    © 2015 Facebook Inc.

    Tutorial #

    Edit on GitHub

    Preface #

    This tutorial aims to get you up to speed with writing iOS and Android apps using React Native. If you're wondering what React Native is and why Facebook built it, this blog post explains that.

    We assume you have experience writing applications with React. If not, you can learn about it on the React website.

    Setup #

    React Native requires the basic setup explained at React Native Getting Started.

    After installing these dependencies there are two simple commands to get a React Native project all set up for development.

    1. npm install -g react-native-cli

      react-native-cli is a command line interface that does the rest of the set up. It’s installable via npm. This will install react-native as a command in your terminal. You only ever need to do this once.

    2. react-native init AwesomeProject

      This command fetches the React Native source code and dependencies and then creates a new Xcode project in AwesomeProject/iOS/AwesomeProject.xcodeproj and a gradle project in AwesomeProject/android/app.

    Development #

    For iOS, you can now open this new project (AwesomeProject/ios/AwesomeProject.xcodeproj) in Xcode and simply build and run it with ⌘+R. Doing so will also start a Node server which enables live code reloading. With this you can see your changes by pressing ⌘+R in the simulator rather than recompiling in Xcode.

    For Android, run react-native run-android from AwesomeProject to install the generated app on your emulator or device, and start the Node server which enables live code reloading. To see your changes you have to open the rage-shake-menu (either shake the device or press the menu button on devices, press F2 or Page Up for emulator, ⌘+M for Genymotion), and then press Reload JS.

    For this tutorial we'll be building a simple version of the Movies app that fetches 25 movies that are in theaters and displays them in a ListView.

    Hello World #

    react-native init will generate an app with the name of your project, in this case AwesomeProject. This is a simple hello world app. For iOS, you can edit index.ios.js to make changes to the app and then press ⌘+R in the simulator to see the changes. For Android, you can edit index.android.js to make changes to the app and press Reload JS from the rage shake menu to see the changes.

    Mocking data #

    Before we write the code to fetch actual Rotten Tomatoes data let's mock some data so we can get our hands dirty with React Native. At Facebook we typically declare constants at the top of JS files, just below the imports, but feel free to add the following constant wherever you like. In index.ios.js or index.android.js :

    var MOCKED_MOVIES_DATA = [ +Tutorial – React Native | A framework for building native apps using React

    Tutorial #

    Edit on GitHub

    Preface #

    This tutorial aims to get you up to speed with writing iOS and Android apps using React Native. If you're wondering what React Native is and why Facebook built it, this blog post explains that.

    We assume you have experience writing applications with React. If not, you can learn about it on the React website.

    Setup #

    React Native requires the basic setup explained at React Native Getting Started.

    After installing these dependencies there are two simple commands to get a React Native project all set up for development.

    1. npm install -g react-native-cli

      react-native-cli is a command line interface that does the rest of the set up. It’s installable via npm. This will install react-native as a command in your terminal. You only ever need to do this once.

    2. react-native init AwesomeProject

      This command fetches the React Native source code and dependencies and then creates a new Xcode project in AwesomeProject/iOS/AwesomeProject.xcodeproj and a gradle project in AwesomeProject/android/app.

    Development #

    For iOS, you can now open this new project (AwesomeProject/ios/AwesomeProject.xcodeproj) in Xcode and simply build and run it with ⌘+R. Doing so will also start a Node server which enables live code reloading. With this you can see your changes by pressing ⌘+R in the simulator rather than recompiling in Xcode.

    For Android, run react-native run-android from AwesomeProject to install the generated app on your emulator or device, and start the Node server which enables live code reloading. To see your changes you have to open the rage-shake-menu (either shake the device or press the menu button on devices, press F2 or Page Up for emulator, ⌘+M for Genymotion), and then press Reload JS.

    For this tutorial we'll be building a simple version of the Movies app that fetches 25 movies that are in theaters and displays them in a ListView.

    Hello World #

    react-native init will generate an app with the name of your project, in this case AwesomeProject. This is a simple hello world app. For iOS, you can edit index.ios.js to make changes to the app and then press ⌘+R in the simulator to see the changes. For Android, you can edit index.android.js to make changes to the app and press Reload JS from the rage shake menu to see the changes.

    Mocking data #

    Before we write the code to fetch actual Rotten Tomatoes data let's mock some data so we can get our hands dirty with React Native. At Facebook we typically declare constants at the top of JS files, just below the imports, but feel free to add the following constant wherever you like. In index.ios.js or index.android.js :

    var MOCKED_MOVIES_DATA = [ {title: 'Title', year: '2015', posters: {thumbnail: 'http://i.imgur.com/UePbdph.jpg'}}, -];

    Render a movie #

    We're going to render the title, year, and thumbnail for the movie. Since thumbnail is an Image component in React Native, add Image to the list of React imports below.

    import React, { +];

    Render a movie #

    We're going to render the title, year, and thumbnail for the movie. Since thumbnail is an Image component in React Native, add Image to the list of React imports below.

    import React, { AppRegistry, Component, Image, @@ -36,7 +36,7 @@
    -

    Add some styling #

    Great, we've rendered our data. Now let's make it look better. I'd like to put the text to the right of the image and make the title larger and centered within that area:

    +---------------------------------+ +

    Add some styling #

    Great, we've rendered our data. Now let's make it look better. I'd like to put the text to the right of the image and make the title larger and centered within that area:

    +---------------------------------+ |+-------++----------------------+| || || Title || || Image || || @@ -73,7 +73,7 @@
    -

    Fetching real data #

    Fetching data from Rotten Tomatoes's API isn't really relevant to learning React Native so feel free to breeze through this section.

    Add the following constants to the top of the file (typically below the imports) to create the REQUEST_URL used to request data with.

    /** +

    Fetching real data #

    Fetching data from Rotten Tomatoes's API isn't really relevant to learning React Native so feel free to breeze through this section.

    Add the following constants to the top of the file (typically below the imports) to create the REQUEST_URL used to request data with.

    /** * For quota reasons we replaced the Rotten Tomatoes' API with a sample data of * their very own API that lives in React Native's Github repo. */ @@ -130,7 +130,7 @@
    -

    ListView #

    Let's now modify this application to render all of this data in a ListView component, rather than just rendering the first movie.

    Why is a ListView better than just rendering all of these elements or putting them in a ScrollView? Despite React being fast, rendering a possibly infinite list of elements could be slow. ListView schedules rendering of views so that you only display the ones on screen and those already rendered but off screen are removed from the native view hierarchy.

    First things first: add the ListView import to the top of the file.

    import React, { +

    ListView #

    Let's now modify this application to render all of this data in a ListView component, rather than just rendering the first movie.

    Why is a ListView better than just rendering all of these elements or putting them in a ScrollView? Despite React being fast, rendering a possibly infinite list of elements could be slow. ListView schedules rendering of views so that you only display the ones on screen and those already rendered but off screen are removed from the native view hierarchy.

    First things first: add the ListView import to the top of the file.

    import React, { AppRegistry, Component, Image, @@ -176,7 +176,7 @@
    -

    There's still some work to be done to make it a fully functional app such as: adding navigation, search, infinite scroll loading, etc. Check the Movies Example to see it all working.

    Final source code #

    /** +

    There's still some work to be done to make it a fully functional app such as: adding navigation, search, infinite scroll loading, etc. Check the Movies Example to see it all working.

    Final source code #

    /** * Sample React Native App * https://github.com/facebook/react-native */ @@ -293,7 +293,7 @@ class AwesomeProject extends }, }); -AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
    © 2015 Facebook Inc.

    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 -version of React Native:

    1. Upgrade the react-native dependency #

    Note the latest version of the react-native npm package from here (or use npm info react-native to check):

    Now install that version of react-native in your project with npm install --save. For example, to upgrade to the version 0.18, in a terminal run:

    $ npm install --save react-native@0.18

    2. Upgrade your project templates #

    The new npm package will likely contain updates to the files that are normally generated when you +version of React Native:

    1. Upgrade the react-native dependency #

    Note the latest version of the react-native npm package from here (or use npm info react-native to check):

    Now install that version of react-native in your project with npm install --save. For example, to upgrade to the version 0.18, in a terminal run:

    $ npm install --save react-native@0.18

    2. Upgrade your project templates #

    The new npm package will likely contain updates to the files that are normally generated when you run react-native init, like the iOS and the Android sub-projects. To get these latest changes, run this in a terminal:

    $ react-native upgrade

    This will check your files against the latest template and perform the following:

    • If there is a new file in the template, it is simply created.
    • If a file in the template is identical to your file, it is skipped.
    • If a file is different in your project than the template, you will be prompted; you have options to view a diff between your file and the template file, keep your file or overwrite it with the -template version. If you are unsure, press h to get a list of possible commands.

    Manual Upgrades #

    Xcode project format is pretty complex and sometimes it's tricky to upgrade and merge new changes.

    From 0.13 to 0.14 #

    The major change in this version happened to the CLI (see changelog) and static images (see docs). To use the new asset system in existing Xcode project, do the following:

    Add new "Run Script" step to your project's build phases:

    Set the script to

    ../node_modules/react-native/packager/react-native-xcode.sh

    Move main.jsbundle to Trash (it will be generated automatically by Xcode using the script above)

    If you installed Node via nvm, you might experience "react-native: command not found". See issues/3974 for workaround and pull/4015 for the fix.

    © 2015 Facebook Inc.

    VibrationIOS #

    Edit on GitHub

    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

    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() #

    Examples #

    Edit on GitHub
    'use strict'; +simulator.

    Vibration patterns are currently unsupported.

    Methods #

    static vibrate() #

    Examples #

    Edit on GitHub
    'use strict'; var React = require('react-native'); var { @@ -39,7 +39,7 @@ exports.examples : '#eeeeee', padding: 10, }, -});
    © 2015 Facebook Inc.

    Videos #

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

    Videos #

    Edit on GitHub
    @@ -12,16 +12,16 @@ -

    The Changelog #149 #

    With Christopher "vjeux" Chedeau and Spencer Ahrens

    +

    The Changelog #149 #

    With Christopher "vjeux" Chedeau and Spencer Ahrens

    -

    JSJabber #146 #

    With Christopher "vjeux" Chedeau and Jordan Walke

    JSJabber #146 #

    With Christopher "vjeux" Chedeau and Jordan Walke

    -
    © 2015 Facebook Inc.

    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 @@ -9,16 +9,16 @@ wraps two colored boxes and custom component in a row with padding.

    ={{backgroundColor: 'red', flex: 0.5}} /> <MyCustomComponent {...customProps} /> </View>

    Views are designed to be used with StyleSheets for clarity and -performance, although inline styles are also supported.

    Props #

    accessibilityLabel string #

    Overrides the text that's read by the screen reader when the user interacts +performance, although inline styles are also supported.

    Props #

    accessibilityLabel string #

    Overrides the text that's read by the screen reader when the user interacts with the element. By default, the label is constructed by traversing all the -children and accumulating all the Text nodes separated by space.

    accessible bool #

    When true, indicates that the view is an accessibility element. By default, -all the touchable elements are accessible.

    onAccessibilityTap function #

    When accessible is true, the system will try to invoke this function -when the user performs accessibility tap gesture.

    onLayout function #

    Invoked on mount and layout changes with

    {nativeEvent: { layout: {x, y, width, height}}}.

    This event is fired immediately once the layout has been calculated, but +children and accumulating all the Text nodes separated by space.

    accessible bool #

    When true, indicates that the view is an accessibility element. By default, +all the touchable elements are accessible.

    onAccessibilityTap function #

    When accessible is true, the system will try to invoke this function +when the user performs accessibility tap gesture.

    onLayout function #

    Invoked on mount and layout changes with

    {nativeEvent: { layout: {x, y, width, height}}}.

    This event is fired immediately once the layout has been calculated, but the new layout may not yet be reflected on the screen at the time the -event is received, especially if a layout animation is in progress.

    onMagicTap function #

    When accessible is true, the system will invoke this function when the -user performs the magic tap gesture.

    onMoveShouldSetResponder function #

    onMoveShouldSetResponderCapture function #

    onResponderGrant function #

    For most touch interactions, you'll simply want to wrap your component in +event is received, especially if a layout animation is in progress.

    onMagicTap function #

    When accessible is true, the system will invoke this function when the +user performs the magic tap gesture.

    onMoveShouldSetResponder function #

    onMoveShouldSetResponderCapture function #

    onResponderGrant function #

    For most touch interactions, you'll simply want to wrap your component in TouchableHighlight or TouchableOpacity. Check out Touchable.js, -ScrollResponder.js and ResponderEventPlugin.js for more discussion.

    onResponderMove function #

    onResponderReject function #

    onResponderRelease function #

    onResponderTerminate function #

    onResponderTerminationRequest function #

    onStartShouldSetResponder function #

    onStartShouldSetResponderCapture function #

    pointerEvents enum('box-none', 'none', 'box-only', 'auto') #

    In the absence of auto property, none is much like CSS's none +ScrollResponder.js and ResponderEventPlugin.js for more discussion.

    onResponderMove function #

    onResponderReject function #

    onResponderRelease function #

    onResponderTerminate function #

    onResponderTerminationRequest function #

    onStartShouldSetResponder function #

    onStartShouldSetResponderCapture function #

    pointerEvents enum('box-none', 'none', 'box-only', 'auto') #

    In the absence of auto property, none is much like CSS's none value. box-none is as if you had applied the CSS class:

    .box-none { pointer-events: none; } @@ -33,23 +33,23 @@ value. box-none is as if you had applied the CSS class already deviating from the spec by adding additional modes, we opt to not include pointerEvents on style. On some platforms, we would need to implement it as a className anyways. Using style or not is an -implementation detail of the platform.

    removeClippedSubviews bool #

    This is a special performance property exposed by RCTView and is useful +implementation detail of the platform.

    removeClippedSubviews bool #

    This is a special performance property exposed by RCTView and is useful for scrolling content when there are many subviews, most of which are offscreen. For this property to be effective, it must be applied to a view that contains many subviews that extend outside its bound. The subviews must also have overflow: hidden, as should the containing view -(or one of its superviews).

    style style #

    backfaceVisibility enum('visible', 'hidden')
    backgroundColor color
    borderBottomColor color
    borderBottomLeftRadius number
    borderBottomRightRadius number
    borderBottomWidth number
    borderColor color
    borderLeftColor color
    borderLeftWidth number
    borderRadius number
    borderRightColor color
    borderRightWidth number
    borderStyle enum('solid', 'dotted', 'dashed')
    borderTopColor color
    borderTopLeftRadius number
    borderTopRightRadius number
    borderTopWidth number
    borderWidth number
    opacity number
    overflow enum('visible', 'hidden')
    androidelevation number

    (Android-only) Sets the elevation of a view, using Android's underlying +(or one of its superviews).

    style style #

    backfaceVisibility enum('visible', 'hidden')
    backgroundColor color
    borderBottomColor color
    borderBottomLeftRadius number
    borderBottomRightRadius number
    borderBottomWidth number
    borderColor color
    borderLeftColor color
    borderLeftWidth number
    borderRadius number
    borderRightColor color
    borderRightWidth number
    borderStyle enum('solid', 'dotted', 'dashed')
    borderTopColor color
    borderTopLeftRadius number
    borderTopRightRadius number
    borderTopWidth number
    borderWidth number
    opacity number
    overflow enum('visible', 'hidden')
    androidelevation number

    (Android-only) Sets the elevation of a view, using Android's underlying elevation API. This adds a drop shadow to the item and affects z-order for overlapping views. -Only supported on Android 5.0+, has no effect on earlier versions.

    testID string #

    Used to locate this view in end-to-end tests. NB: disables the 'layout-only -view removal' optimization for this view!

    androidaccessibilityComponentType AccessibilityComponentType #

    Indicates to accessibility services to treat UI component like a -native one. Works for Android only.

    androidaccessibilityLiveRegion enum('none', 'polite', 'assertive') #

    Indicates to accessibility services whether the user should be notified +Only supported on Android 5.0+, has no effect on earlier versions.

    testID string #

    Used to locate this view in end-to-end tests. NB: disables the 'layout-only +view removal' optimization for this view!

    androidaccessibilityComponentType AccessibilityComponentType #

    Indicates to accessibility services to treat UI component like a +native one. Works for Android only.

    androidaccessibilityLiveRegion enum('none', 'polite', 'assertive') #

    Indicates to accessibility services whether the user should be notified when this view changes. Works for Android API >= 19 only. See http://developer.android.com/reference/android/view/View.html#attr_android:accessibilityLiveRegion -for references.

    androidcollapsable bool #

    Views that are only used to layout their children or otherwise don't draw +for references.

    androidcollapsable bool #

    Views that are only used to layout their children or otherwise don't draw anything may be automatically removed from the native hierarchy as an optimization. Set this property to false to disable this optimization and -ensure that this View exists in the native view hierarchy.

    androidimportantForAccessibility enum('auto', 'yes', 'no', 'no-hide-descendants') #

    Controls how view is important for accessibility which is if it +ensure that this View exists in the native view hierarchy.

    androidimportantForAccessibility enum('auto', 'yes', 'no', 'no-hide-descendants') #

    Controls how view is important for accessibility which is if it fires accessibility events and if it is reported to accessibility services that query the screen. Works for Android only. See http://developer.android.com/reference/android/R.attr.html#importantForAccessibility @@ -60,7 +60,7 @@ Possible values: 'yes' - The view is important for accessibility. 'no' - The view is not important for accessibility. 'no-hide-descendants' - The view is not important for accessibility, - nor are any of its descendant views.

    androidneedsOffscreenAlphaCompositing bool #

    Whether this view needs to rendered offscreen and composited with an alpha + nor are any of its descendant views.

    androidneedsOffscreenAlphaCompositing bool #

    Whether this view needs to rendered offscreen and composited with an alpha in order to preserve 100% correct colors and blending behavior. The default (false) falls back to drawing the component and its children with an alpha applied to the paint used to draw each element instead of rendering the full @@ -74,20 +74,20 @@ animation, consider combining it with renderToHardwareTextureAndroid if the view contents are static (i.e. it doesn't need to be redrawn each frame). If that property is enabled, this View will be rendered off-screen once, saved in a hardware texture, and then composited onto the screen with an alpha -each frame without having to switch rendering targets on the GPU.

    androidrenderToHardwareTextureAndroid bool #

    Whether this view should render itself (and all of its children) into a +each frame without having to switch rendering targets on the GPU.

    androidrenderToHardwareTextureAndroid bool #

    Whether this view should render itself (and all of its children) into a single hardware texture on the GPU.

    On Android, this is useful for animations and interactions that only modify opacity, rotation, translation, and/or scale: in those cases, the view doesn't have to be redrawn and display lists don't need to be re-executed. The texture can just be re-used and re-composited with different parameters. The downside is that this can use up limited video memory, so this prop should be set back to false at the end of the -interaction/animation.

    iosaccessibilityTraits AccessibilityTraits, [AccessibilityTraits] #

    Provides additional traits to screen reader. By default no traits are -provided unless specified otherwise in element

    iosshouldRasterizeIOS bool #

    Whether this view should be rendered as a bitmap before compositing.

    On iOS, this is useful for animations and interactions that do not +interaction/animation.

    iosaccessibilityTraits AccessibilityTraits, [AccessibilityTraits] #

    Provides additional traits to screen reader. By default no traits are +provided unless specified otherwise in element

    iosshouldRasterizeIOS bool #

    Whether this view should be rendered as a bitmap before compositing.

    On iOS, this is useful for animations and interactions that do not modify this component's dimensions nor its children; for example, when translating the position of a static view, rasterization allows the renderer to reuse a cached bitmap of a static view and quickly composite it during each frame.

    Rasterization incurs an off-screen drawing pass and the bitmap consumes -memory. Test and measure when using this property.

    Examples #

    Edit on GitHub
    'use strict'; +memory. Test and measure when using this property.

    Examples #

    Edit on GitHub
    'use strict'; var Platform = require('Platform'); var React = require('react-native'); @@ -263,7 +263,7 @@ exports.examples ); }, }, -];
    © 2015 Facebook Inc.

    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 @@ -25,24 +25,24 @@ child.

    Example:

    render: 'center', padding: 20, } -}

    Props #

    initialPage number #

    Index of initial page that should be selected. Use setPage method to -update the page, and onPageSelected to monitor page changes

    keyboardDismissMode enum('none', 'on-drag') #

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

    Props #

    initialPage number #

    Index of initial page that should be selected. Use setPage method to +update the page, and onPageSelected to monitor page changes

    keyboardDismissMode enum('none', 'on-drag') #

    Determines whether the keyboard gets dismissed in response to a drag. - 'none' (the default), drags do not dismiss the keyboard. - - 'on-drag', the keyboard is dismissed when a drag begins.

    onPageScroll function #

    Executed when transitioning between pages (ether because of animation for + - 'on-drag', the keyboard is dismissed when a drag begins.

    onPageScroll function #

    Executed when transitioning between pages (ether because of animation for the requested page change or when user is swiping/dragging between pages) The event.nativeEvent object for this callback will carry following data: - position - index of first page from the left that is currently visible - offset - value from range [0,1) describing stage between page transitions. Value x means that (1 - x) fraction of the page at "position" index is - visible, and x fraction of the next page is visible.

    onPageScrollStateChanged function #

    Function called when the page scrolling state has changed. + visible, and x fraction of the next page is visible.

    onPageScrollStateChanged function #

    Function called when the page scrolling state has changed. The page scrolling state can be in 3 states: - idle, meaning there is no interaction with the page scroller happening at the time - dragging, meaning there is currently an interaction with the page scroller - settling, meaning that there was an interaction with the page scroller, and the - page scroller is now finishing it's closing or opening animation

    onPageSelected function #

    This callback will be called once ViewPager finish navigating to selected page + page scroller is now finishing it's closing or opening animation

    onPageSelected function #

    This callback will be called once ViewPager finish navigating to selected page (when user swipes between pages). The event.nativeEvent object passed to this callback will have following fields: - - position - index of page that has been selected

    Examples #

    Edit on GitHub
    'use strict'; + - position - index of page that has been selected

    Examples #

    Edit on GitHub
    'use strict'; var React = require('react-native'); var { @@ -290,7 +290,7 @@ import type { ViewPagerScrollState }, }); -module.exports = ViewPagerAndroidExample;
    © 2015 Facebook Inc.

    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.

    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.

    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 +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.

    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.

    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 NOTE : "In order for video to play inline, not only does this property need to be set to true, but the video element in the HTML -document must also include the webkit-playsinline attribute."

    iosbounces bool #

    iosdecelerationRate ScrollView.propTypes.decelerationRate #

    A floating-point number that determines how quickly the scroll view +document must also include the webkit-playsinline attribute."

    iosbounces bool #

    iosdecelerationRate ScrollView.propTypes.decelerationRate #

    A floating-point number that determines how quickly the scroll view decelerates after the user lifts their finger. You may also use string shortcuts "normal" and "fast" which match the underlying iOS settings for UIScrollViewDecelerationRateNormal and UIScrollViewDecelerationRateFast respectively. - Normal: 0.998 - - Fast: 0.9 (the default for iOS WebView)

    iosonShouldStartLoadWithRequest function #

    Allows custom handling of any webview requests by a JS handler. Return true -or false from this method to continue loading the request.

    iosscalesPageToFit bool #

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

    iosscrollEnabled bool #

    Examples #

    Edit on GitHub
    'use strict'; + - Fast: 0.9 (the default for iOS WebView)

    iosonShouldStartLoadWithRequest function #

    Allows custom handling of any webview requests by a JS handler. Return true +or false from this method to continue loading the request.

    iosscalesPageToFit bool #

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

    iosscrollEnabled bool #

    Examples #

    Edit on GitHub
    'use strict'; var React = require('react-native'); var { @@ -313,7 +313,7 @@ exports.examples ); } } -];
    © 2015 Facebook Inc.
    React Native
    A framework for building native apps using React

    React Native enables you to build world-class application experiences on native platforms using a consistent developer experience based on JavaScript and React. The focus of React Native is on developer efficiency across all the platforms you care about — learn once, write anywhere. Facebook uses React Native in multiple production apps and will continue investing in React Native.

    Native Components

    With React Native, you can use the standard platform components such as UITabBar on iOS and Drawer on Android. This gives your app a consistent look and feel with the rest of the platform ecosystem, and keeps the quality bar high. These components are easily incorporated into your app using their React component counterparts, such as TabBarIOS and DrawerLayoutAndroid.

    // iOS +React Native | A framework for building native apps using React
    React Native
    A framework for building native apps using React

    React Native enables you to build world-class application experiences on native platforms using a consistent developer experience based on JavaScript and React. The focus of React Native is on developer efficiency across all the platforms you care about — learn once, write anywhere. Facebook uses React Native in multiple production apps and will continue investing in React Native.

    Native Components

    With React Native, you can use the standard platform components such as UITabBar on iOS and Drawer on Android. This gives your app a consistent look and feel with the rest of the platform ecosystem, and keeps the quality bar high. These components are easily incorporated into your app using their React component counterparts, such as TabBarIOS and DrawerLayoutAndroid.

    // iOS var React = require('react-native'); var { TabBarIOS, NavigatorIOS } = React; @@ -235,7 +235,7 @@ MyCustomView.propTypes var NativeMyCustomView = requireNativeComponent('MyCustomView', MyCustomView); module.exports = MyCustomView; -
    © 2015 Facebook Inc.

    Apps using React Native

    The following is a list of some of the public apps using React Native and are published on the Apple App Store or the Google Play Store. Not all are implemented 100% in React Native -- many are hybrid native/React Native. Can you tell which parts are which? :)

    Want to add your app? Found an app that no longer works or no longer uses React Native? Please submit a pull request on GitHub to update this page!

    Featured Apps

    These are some of the most well-crafted React Native apps that we have come across.
    Be sure to check them out to get a feel for what React Native is capable of!

    All Apps

    Not all apps can be featured, otherwise we would have to create some other category like "super featured" and that's just silly. But that doesn't mean you shouldn't check these apps out!

    CANDDi

    CANDDi

    iOS -Android

    By CANDDi LTD.

    DockMan

    DockMan

    iOS -Android

    By Genki Takiuchi (s21g Inc.)

    Blog post

    Eat or Not

    Eat or Not

    iOS -Android

    By Sharath Prabhal

    Kakapo

    Kakapo

    iOS -Android

    By Daniel Levitt

    LoadDocs

    LoadDocs

    iOS -Android

    By LoadDocs

    MaxReward - Android

    MaxReward - Android

    iOS -Android

    By Neil Ma

    ShareHows

    ShareHows

    iOS -Android

    By Dobbit Co., Ltd.

    WEARVR

    WEARVR

    iOS -Android

    By WEARVR LLC

    天才段子手

    天才段子手

    iOS -Android

    By Ran Zhao&Ji Zhao

    うたよみん

    うたよみん

    iOS -Android

    By Takayuki IMAI

    © 2015 Facebook Inc.

    Apps using React Native

    The following is a list of some of the public apps using React Native and are published on the Apple App Store or the Google Play Store. Not all are implemented 100% in React Native -- many are hybrid native/React Native. Can you tell which parts are which? :)

    Want to add your app? Found an app that no longer works or no longer uses React Native? Please submit a pull request on GitHub to update this page!

    Featured Apps

    These are some of the most well-crafted React Native apps that we have come across.
    Be sure to check them out to get a feel for what React Native is capable of!

    All Apps

    Not all apps can be featured, otherwise we would have to create some other category like "super featured" and that's just silly. But that doesn't mean you shouldn't check these apps out!

    CANDDi

    CANDDi

    iOS - Android

    By CANDDi LTD.

    DockMan

    DockMan

    iOS - Android

    By Genki Takiuchi (s21g Inc.)

    Blog post

    Fixt

    Fixt

    iOS - Android

    By Fixt

    Eat or Not

    Eat or Not

    iOS - Android

    By Sharath Prabhal

    Kakapo

    Kakapo

    iOS - Android

    By Daniel Levitt

    LoadDocs

    LoadDocs

    iOS - Android

    By LoadDocs

    MaxReward - Android

    MaxReward - Android

    iOS - Android

    By Neil Ma

    ShareHows

    ShareHows

    iOS - Android

    By Dobbit Co., Ltd.

    WEARVR

    WEARVR

    iOS - Android

    By WEARVR LLC

    天才段子手

    天才段子手

    iOS - Android

    By Ran Zhao&Ji Zhao

    うたよみん

    うたよみん

    iOS - Android

    By Takayuki IMAI

    © 2016 Facebook Inc.

    Need help?

    React Native is worked on full-time by Facebook's product infrastructure user interface engineering teams. They're often around and available for questions.

    Community translation #

    The following is a list of translated docs offered by community volunteers. Send a pull request to fill the list!

    Stack Overflow #

    Many members of the community use Stack Overflow to ask questions. Read through the existing questions tagged with react-native or ask your own!

    Chat #

    Join us in #reactnative on Reactiflux.

    Twitter #

    #reactnative hash tag on Twitter is used to keep up with the latest React Native news.

    © 2015 Facebook Inc.

    Need help?

    React Native is worked on full-time by Facebook's product infrastructure user interface engineering teams. They're often around and available for questions.

    Community translation #

    The following is a list of translated docs offered by community volunteers. Send a pull request to fill the list!

    Stack Overflow #

    Many members of the community use Stack Overflow to ask questions. Read through the existing questions tagged with react-native or ask your own!

    Chat #

    Join us in #reactnative on Reactiflux.

    Twitter #

    #reactnative hash tag on Twitter is used to keep up with the latest React Native news.

    © 2016 Facebook Inc.