diff --git a/docs/0.10/accessibility.html b/docs/0.10/accessibility.html
index cae0646c0a7..43efbd79155 100644
--- a/docs/0.10/accessibility.html
+++ b/docs/0.10/accessibility.html
@@ -11,7 +11,7 @@
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}’.
+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>
@@ -61,7 +61,7 @@
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.
+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. We support 'none', ‘button’, ‘radiobutton_checked’ and ‘radiobutton_unchecked’.
<TouchableWithoutFeedback accessibilityComponentType=”button”
onPress={this._onPress}>
<View style={styles.button}>
@@ -105,13 +105,20 @@
The AccessibilityInfo API allows you to determine whether or not a screen reader is currently active. See the AccessibilityInfo documentation for details.
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”) {
- RCTUIManager.sendAccessibilityEvent(
- ReactNative.findNodeHandle(this ),
- RCTUIManager.AccessibilityEventTypes.typeViewClicked);
+import { UIManager, findNodeHandle } from 'react-native' ;
+
+_onPress: function ( ) {
+ const radioButton = this .state.radioButton === 'radiobutton_checked' ?
+ 'radiobutton_unchecked' : 'radiobutton_checked'
+
+ this .setState({
+ radioButton : radioButton
+ });
+
+ if (radioButton === 'radiobutton_checked' ) {
+ UIManager.sendAccessibilityEvent(
+ findNodeHandle(this ),
+ UIManager.AccessibilityEventTypes.typeViewClicked);
}
}
diff --git a/docs/0.10/animations.html b/docs/0.10/animations.html
index 05eee1d6971..ce0d80f12df 100644
--- a/docs/0.10/animations.html
+++ b/docs/0.10/animations.html
@@ -5,7 +5,7 @@
nav.classList.toggle('docsSliderActive');
};
Animations are very important to create a great user experience. Stationary objects must overcome inertia as they start moving. Objects in motion have momentum and rarely come to a stop immediately. Animations allow you to convey physically believable motion in your interface.
-React Native provides two complementary animation systems: Animated for granular and interactive control of specific values, and LayoutAnimation for animated global layout transactions.
+React Native provides two complementary animation systems: Animated for granular and interactive control of specific values, and LayoutAnimation for animated global layout transactions.
Animated API
The Animated API 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 methods to control time-based animation execution.
Animated exports four animatable component types: View, Text, Image, and ScrollView, but you can also create your own using Animated.createAnimatedComponent().
diff --git a/docs/0.10/app-extensions.html b/docs/0.10/app-extensions.html
index abf6705054c..8d2aad7beca 100644
--- a/docs/0.10/app-extensions.html
+++ b/docs/0.10/app-extensions.html
@@ -10,7 +10,7 @@
We highly recommend that you watch Conrad Kramer's talk on Memory Use in Extensions to learn more about this topic.
Today widget
The memory limit of a Today widget is 16 MB. As it happens, Today widget implementations using React Native may work unreliably because the memory usage tends to be too high. You can tell if your Today widget is exceeding the memory limit if it yields the message 'Unable to Load':
-
+
Always make sure to test your app extensions in a real device, but be aware that this may not be sufficient, especially when dealing with Today widgets. Debug-configured builds are more likely to exceed the memory limits, while release-configured builds don't fail right away. We highly recommend that you use Xcode's Instruments to analyze your real world memory usage, as it's very likely that your release-configured build is very close to the 16 MB limit. In situations like these, it is easy to go over the 16 MB limit by performing common operations, such as fetching data from an API.
To experiment with the limits of React Native Today widget implementations, try extending the example project in react-native-today-widget .
Other app extensions
diff --git a/docs/0.10/building-for-apple-tv.html b/docs/0.10/building-for-apple-tv.html
index ca6b67025d9..587e2b3713a 100644
--- a/docs/0.10/building-for-apple-tv.html
+++ b/docs/0.10/building-for-apple-tv.html
@@ -1,10 +1,82 @@
-Building For Apple TV · React Native Apple TV support has been implemented with the intention of making existing React Native iOS applications "just work" on tvOS, with few or no changes needed in the JavaScript code for the applications.
+
+TV devices support has been implemented with the intention of making existing React Native applications "just work" on Apple TV and Android TV, with few or no changes needed in the JavaScript code for the applications.
+
+
+
+ iOS
+
+
+ Android
+
+
+
+
The RNTester app supports Apple TV; use the RNTester-tvOS build target to build for tvOS.
Build changes
@@ -12,10 +84,41 @@
react-native init : New React Native projects created with react-native init will have Apple TV target automatically created in their XCode projects.
JavaScript layer : Support for Apple TV has been added to Platform.ios.js. You can check whether code is running on AppleTV by doing
-var Platform = require ('Platform' );
+var Platform = require ('Platform' );
+var running_on_tv = Platform.isTV;
+
+
+
var running_on_apple_tv = Platform.isTVOS;
+
+ Build changes
+
+Native layer : To run React Native project on Android TV make sure to make the following changes to AndroidManifest.xml
+
+
+ <application
+ ...
+ android:banner ="@drawable/tv_banner"
+ >
+ ...
+ <intent-filter >
+ ...
+
+ <category android:name ="android.intent.category.LEANBACK_LAUNCHER" />
+ </intent-filter >
+ ...
+ </application >
+
+
+JavaScript layer : Support for Android TV has been added to Platform.android.js. You can check whether code is running on Android TV by doing
+
+var Platform = require ('Platform' );
+var running_on_android_tv = Platform.isTV;
+
+
Code changes
+
General support for tvOS : Apple TV specific changes in native code are all wrapped by the TARGET_OS_TV define. These include changes to suppress APIs that are not supported on tvOS (e.g. web views, sliders, switches, status bar, etc.), and changes to support user input from the TV remote or keyboard.
Common codebase : Since tvOS and iOS share most Objective-C and JavaScript code in common, most documentation for iOS applies equally to tvOS.
@@ -25,9 +128,26 @@
touchableHandleActivePressOut will be executed when the touchable view goes out of focus
touchableHandlePress will be executed when the touchable view is actually selected by pressing the "select" button on the TV remote.
-TV remote/keyboard input : A new native class, RCTTVRemoteHandler, sets up gesture recognizers for TV remote events. When TV remote events occur, this class fires notifications that are picked up by RCTTVNavigationEventEmitter (a subclass of RCTEventEmitter), that fires a JS event. This event will be picked up by instances of the TVEventHandler JavaScript object. Application code that needs to implement custom handling of TV remote events can create an instance of TVEventHandler and listen for these events, as in the following code:
-var TVEventHandler = require ('TVEventHandler' );
+
+
+Access to touchable controls : When running on Android TV the Android framework will automatically apply a directional navigation scheme based on relative position of focusable elements in your views. The Touchable mixin has code added to detect focus changes and use existing methods to style the components properly and initiate the proper actions when the view is selected using the TV remote, so TouchableHighlight, TouchableOpacity and TouchableNativeFeedback will "just work". In particular:
+
+touchableHandleActivePressIn will be executed when the touchable view goes into focus
+touchableHandleActivePressOut will be executed when the touchable view goes out of focus
+touchableHandlePress will be executed when the touchable view is actually selected by pressing the "select" button on the TV remote.
+
+
+
+
+TV remote/keyboard input : A new native class, RCTTVRemoteHandler, sets up gesture recognizers for TV remote events. When TV remote events occur, this class fires notifications that are picked up by RCTTVNavigationEventEmitter (a subclass of RCTEventEmitter), that fires a JS event. This event will be picked up by instances of the TVEventHandler JavaScript object. Application code that needs to implement custom handling of TV remote events can create an instance of TVEventHandler and listen for these events, as in the following code:
+
+
+
+TV remote/keyboard input : A new native class, ReactAndroidTVRootViewHelper, sets up key events handlers for TV remote events. When TV remote events occur, this class fires a JS event. This event will be picked up by instances of the TVEventHandler JavaScript object. Application code that needs to implement custom handling of TV remote events can create an instance of TVEventHandler and listen for these events, as in the following code:
+
+
+var TVEventHandler = require ('TVEventHandler' );
.
.
@@ -68,16 +188,115 @@ class Game2048 extends React.Component {
this ._disableTVEventHandler();
}
+
Dev Menu support : On the simulator, cmd-D will bring up the developer menu, just like on iOS. To bring it up on a real Apple TV device, make a long press on the play/pause button on the remote. (Please do not shake the Apple TV device, that will not work :) )
TV remote animations : RCTTVView native code implements Apple-recommended parallax animations to help guide the eye as the user navigates through views. The animations can be disabled or adjusted with new optional view properties.
Back navigation with the TV remote menu button : The BackHandler component, originally written to support the Android back button, now also supports back navigation on the Apple TV using the menu button on the TV remote.
TabBarIOS behavior : The TabBarIOS component wraps the native UITabBar API, which works differently on Apple TV. To avoid jittery rerendering of the tab bar in tvOS (see this issue ), the selected tab bar item can only be set from Javascript on initial render, and is controlled after that by the user through native code.
+
+
+
+Dev Menu support : On the simulator, cmd-M will bring up the developer menu, just like on Android. To bring it up on a real Android TV device, make a long press on the play/pause button on the remote. (Please do not shake the Android TV device, that will not work :) )
+
+
+
Known issues :
ListView scrolling . The issue can be easily worked around by setting removeClippedSubviews to false in ListView and similar components. For more discussion of this issue, see this PR .
+
+
+Known issues :
+
+InputText components do not work for now (i.e. they cannot receive focus).
+
+
+
Headless JS is a way to run tasks in JavaScript while your app is in the background. It can be used, for example, to sync fresh data, handle push notifications, or play music.
The JS API
A task is a simple async function that you register on AppRegistry, similar to registering React applications:
-AppRegistry.registerHeadlessTask('SomeTaskName' , () => require ('SomeTaskName' ));
+AppRegistry.registerHeadlessTask('SomeTaskName' , () => require ('SomeTaskName' ));
Then, in SomeTaskName.js:
-module .exports = async (taskData) => {
+module .exports = async (taskData) => {
};
diff --git a/docs/0.10/height-and-width.html b/docs/0.10/height-and-width.html
index b4969d71bef..16527986421 100644
--- a/docs/0.10/height-and-width.html
+++ b/docs/0.10/height-and-width.html
@@ -5,7 +5,7 @@
nav.classList.toggle('docsSliderActive');
};
A component's height and width determine its size on the screen.
- Fixed Dimensions
+ Fixed Dimensions
The simplest way to set the dimensions of a component is by adding a fixed width and height to style. All dimensions in React Native are unitless, and represent density-independent pixels.
import React, { Component } from 'react' ;
import { AppRegistry, View } from 'react-native' ;
@@ -27,7 +27,7 @@ AppRegistry.registerComponent('AwesomeProject', () => FixedDimensionsBasics);
Setting dimensions this way is common for components that should always render at exactly the same size, regardless of screen dimensions.
- Flex Dimensions
+ Flex Dimensions
Use flex in a component's style to have the component expand and shrink dynamically based on available space. Normally you will use flex: 1, which tells a component to fill all available space, shared evenly amongst each other component with the same parent. The larger the flex given, the higher the ratio of space a component will take compared to its siblings.
A component can only expand to fill available space if its parent has dimensions greater than 0. If a parent does not have either a fixed width and height or flex, the parent will have dimensions of 0 and the flex children will not be visible.
diff --git a/docs/0.10/images.html b/docs/0.10/images.html
index e1e36f1ab07..dfd614fa54f 100644
--- a/docs/0.10/images.html
+++ b/docs/0.10/images.html
@@ -47,8 +47,8 @@ var icon = this.props.active
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.
Static Non-Image Resources
-The require syntax described above can be used to statically include audio, video or document files in your project as well. Most common file types are supported including .mp3, .wav, .mp4, .mov, .html and .pdf. See packager defaults for the full list.
-You can add support for other types by creating a packager config file (see the packager config file for the full list of configuration options).
+The require syntax described above can be used to statically include audio, video or document files in your project as well. Most common file types are supported including .mp3, .wav, .mp4, .mov, .html and .pdf. See packager defaults for the full list.
+You can add support for other types by creating a packager config file (see the packager config file for the full list of configuration options).
A caveat is that videos must use absolute positioning instead of flexGrow, since size info is not currently passed for non-image assets. This limitation doesn't occur for videos that are linked directly into Xcode or the Assets folder for Android.
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.
diff --git a/docs/0.10/improvingux.html b/docs/0.10/improvingux.html
index 2e07da66ba7..39ccabfb7b0 100644
--- a/docs/0.10/improvingux.html
+++ b/docs/0.10/improvingux.html
@@ -18,7 +18,7 @@
Configure text inputs
-Entering text on touch phone is a challange - small screen, software keyboard. But based on what kind of data you need, you can make it easier by properly configuring the text inputs:
+Entering text on touch phone is a challenge - small screen, software keyboard. But based on what kind of data you need, you can make it easier by properly configuring the text inputs:
Focus the first field automatically
Use placeholder text as an example of expected data format
@@ -41,6 +41,8 @@
Android API 21+ uses the material design ripple to provide user with feedback when they touch an interactable area on the screen. React Native exposes this through the TouchableNativeFeedback component . Using this touchable effect instead of opacity or highlight will often make your app feel much more fitting on the platform. That said, you need to be careful when using it because it doesn't work on iOS or on Android API < 21, so you will need to fallback to using one of the other Touchable components on iOS. You can use a library like react-native-platform-touchable to handle the platform differences for you.
Try it on your phone
+ Screen orientation lock
+Unless supporting both, it is considered good practice to lock the screen orientation to either portrait or landscape. On iOS, in the General tab and Deployment Info section of Xcode enable the Device Orientation you want to support (ensure you have selected iPhone from the Devices menu when making the changes). For Android, open the AndroidManifest.xml file and within the activity element add 'android:screenOrientation=”portrait”' to lock to portrait or 'android:screenOrientation=”landscape”' to lock to landscape.
Learn more
Material Design and Human Interface Guidelines are great resources for learning more about designing for mobile platforms.
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 .
+In most cases, React Native will use JavaScriptCore , the JavaScript engine that powers Safari. Note that on iOS, JavaScriptCore does not use JIT due to the absence of writable executable memory in iOS apps.
+When using Chrome debugging, all JavaScript code runs within Chrome itself, communicating with native code via WebSockets. Chrome uses V8 as its JavaScript engine.
-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.
+While both environments are very similar, you may end up hitting some inconsistencies. We're likely going to experiment with other JavaScript 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.
+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
-ES7
+ES8
+Stage 3
+
Specific
-JSX : <View style={{color: 'red'}} />
+JSX : <View style={{color: 'red'}} />
Flow : function foo(x: ?number): string {}
Polyfills
@@ -59,12 +62,16 @@
ES6
ES7
+ES8
+
Specific
diff --git a/docs/0.10/more-resources.html b/docs/0.10/more-resources.html
index b6000c621c4..c2dc51c8ed0 100644
--- a/docs/0.10/more-resources.html
+++ b/docs/0.10/more-resources.html
@@ -8,16 +8,16 @@
Popular Libraries
If you're using React Native, you probably already know about React . So I feel a bit silly mentioning this. But if you haven't, check out React - it's the best way to build a modern website.
One common question is how to handle the "state" of your React Native application. The most popular library for this is Redux . Don't be afraid of how often Redux uses the word "reducer" - it's a pretty simple library, and there's also a nice series of videos explaining it.
-If you're looking for a library that does a specific thing, check out Awesome React Native , a curated list of components that also has demos, articles, and other stuff. You can also find a curated list of React Native libraries at Native Directory , together with quality assessment, recommendations, a lot of pertinent GitHub information, and code examples.
+If you're looking for a library that does a specific thing, check out Awesome React Native , a curated list of components that also has demos, articles, and other stuff.
Examples
Try out apps from the Showcase to see what React Native is capable of! There are also some example apps on GitHub . You can run the apps on a simulator or device, and you can see the source code for these apps, which is neat.
-The folks who built the app for Facebook's F8 conference in 2016 also open-sourced the code and wrote up a detailed series of tutorials . This is useful if you want a more in-depth example that's more realistic than most sample apps out there.
+The folks who built the app for Facebook's F8 conference also open-sourced the code and wrote up a detailed series of tutorials . This is useful if you want a more in-depth example that's more realistic than most sample apps out there.
Extending React Native
-Looking for a component? JS.coach
Fellow developers write and publish React Native modules to npm and open source them on GitHub.
Making modules helps grow the React Native ecosystem and community. We recommend writing modules for your use cases and sharing them on npm.
Read the guides on Native Modules (iOS , Android ) and Native UI Components (iOS , Android ) if you are interested in extending native functionality.
+Looking for a pre-built component? Check JS.coach .
Development Tools
Nuclide is the IDE that Facebook uses internally for JavaScript development. The killer feature of Nuclide is its debugging ability. It also has great inline Flow support. VS Code is another IDE that is popular with JavaScript developers.
diff --git a/docs/0.10/native-components-android.html b/docs/0.10/native-components-android.html
index 68fab8aba7c..08289d8b5da 100644
--- a/docs/0.10/native-components-android.html
+++ b/docs/0.10/native-components-android.html
@@ -71,10 +71,10 @@
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.
-
+
import PropTypes from 'prop-types' ;
-import {requireNativeComponent, View} from 'react-native' ;
+import {requireNativeComponent, ViewPropTypes} from 'react-native' ;
var iface = {
name : 'ImageView' ,
@@ -82,7 +82,7 @@
src : PropTypes.string,
borderRadius : PropTypes.number,
resizeMode : PropTypes.oneOf(['cover' , 'contain' , 'stretch' ]),
- ...View.propTypes,
+ ...ViewPropTypes,
},
};
@@ -119,7 +119,7 @@
}
This callback is invoked with the raw event, which we typically process in the wrapper component to make a simpler API:
-
+
class MyCustomView extends React .Component {
constructor (props) {
diff --git a/docs/0.10/native-modules-android.html b/docs/0.10/native-modules-android.html
index 6ecf2117737..f50e6022164 100644
--- a/docs/0.10/native-modules-android.html
+++ b/docs/0.10/native-modules-android.html
@@ -107,7 +107,7 @@ ReadableArray -><
}
To make it simpler to access your new functionality from JavaScript, it is common to wrap the native module in a JavaScript module. This is not necessary but saves the consumers of your library the need to pull it off of NativeModules each time. This JavaScript file also becomes a good location for you to add any JavaScript side functionality.
-Mobile apps are rarely made up of a single screen. Managing the presentation of, and transition between, multiple screens is typically handled by what is known as a navigator.
-This guide covers the various navigation components available in React Native. If you are just getting started with navigation, you will probably want to use React Navigation . React Navigation provides an easy to use navigation solution, with the ability to present common stack navigation and tabbed navigation patterns on both iOS and Android. As this is a JavaScript implementation, it provides the greatest amount of configurability as well as flexibility when integrating with state management libraries such as redux .
+This guide covers the various navigation components available in React Native. If you are just getting started with navigation, you will probably want to use React Navigation . React Navigation provides an easy to use navigation solution, with the ability to present common stack navigation and tabbed navigation patterns on both iOS and Android. As this is a JavaScript implementation, it provides the greatest amount of configurability as well as flexibility when integrating with state management libraries such as redux .
If you're only targeting iOS, you may want to also check out NavigatorIOS as a way of providing a native look and feel with minimal configuration, as it provides a wrapper around the native UINavigationController class. This component will not work on Android, however.
If you'd like to achieve a native look and feel on both iOS and Android, or you're integrating React Native into an app that already manages navigation natively, the following libraries provide native navigation on both platforms: native-navigation , react-native-navigation .
React Navigation
@@ -43,10 +43,10 @@ const App = StackNavigator({
React Navigation routers make it easy to override navigation logic or integrate it into redux. Because routers can be nested inside each other, developers can override navigation logic for one area of the app without making widespread changes.
The views in React Navigation use native components and the Animated library to deliver 60fps animations that are run on the native thread. Plus, the animations and gestures can be easily customized.
-For a complete intro to React Navigation, follow the React Navigation Getting Started Guide , or browse other docs such as the Intro to Navigators .
+For a complete intro to React Navigation, follow the React Navigation Getting Started Guide , or browse other docs such as the Intro to Navigators .
NavigatorIOS
NavigatorIOS looks and feels just like UINavigationController , because it is actually built on top of it.
-
+
<NavigatorIOS
initialRoute={{
component : MyScene,
diff --git a/docs/0.10/network.html b/docs/0.10/network.html
index 90525ee765e..e3f6ad5a406 100644
--- a/docs/0.10/network.html
+++ b/docs/0.10/network.html
@@ -9,10 +9,10 @@
React Native provides the Fetch API for your networking needs. Fetch will seem familiar if you have used XMLHttpRequest or other networking APIs before. You may refer to MDN's guide on Using Fetch for additional information.
Making requests
In order to fetch content from an arbitrary URL, just pass the URL to fetch:
-fetch('https://mywebsite.com/mydata.json' );
+fetch('https://mywebsite.com/mydata.json' );
Fetch also takes an optional second argument that allows you to customize the HTTP request. You may want to specify additional headers, or make a POST request:
-fetch('https://mywebsite.com/endpoint/' , {
+fetch('https://mywebsite.com/endpoint/' , {
method : 'POST' ,
headers : {
Accept : 'application/json' ,
@@ -28,7 +28,7 @@
Handling the response
The above examples show how you can make a request. In many cases, you will want to do something with the response.
Networking is an inherently asynchronous operation. Fetch methods will return a Promise that makes it straightforward to write code that works in an asynchronous manner:
-function getMoviesFromApiAsync ( ) {
+function getMoviesFromApiAsync ( ) {
return fetch('https://facebook.github.io/react-native/movies.json' )
.then((response ) => response.json())
.then((responseJson ) => {
@@ -40,7 +40,7 @@
}
You can also use the proposed ES2017 async/await syntax in a React Native app:
-async function getMoviesFromApi ( ) {
+async function getMoviesFromApi ( ) {
try {
let response = await fetch(
'https://facebook.github.io/react-native/movies.json'
@@ -53,48 +53,52 @@
}
Don't forget to catch any errors that may be thrown by fetch, otherwise they will be dropped silently.
-import React, { Component } from 'react' ;
-import { ActivityIndicator, ListView, Text, View } from 'react-native' ;
+import React from 'react' ;
+import { FlatList, ActivityIndicator, Text, View } from 'react-native' ;
-export default class Movies extends Component {
- constructor (props) {
+export default class FetchExample extends React .Component {
+
+ constructor (props){
super (props);
- this .state = {
- isLoading : true
- }
+ this .state ={ isLoading : true }
}
- componentDidMount() {
+ componentDidMount(){
return fetch('https://facebook.github.io/react-native/movies.json' )
.then((response ) => response.json())
.then((responseJson ) => {
- let ds = new ListView.DataSource({rowHasChanged : (r1, r2 ) => r1 !== r2});
+
this .setState({
isLoading : false ,
- dataSource : ds.cloneWithRows(responseJson.movies),
- }, function ( ) {
-
+ dataSource : responseJson.movies,
+ }, function ( ) {
+
});
+
})
- .catch((error ) => {
+ .catch((error ) => {
console .error(error);
});
}
- render() {
- if (this .state.isLoading) {
- return (
- <View style ={{flex: 1 , paddingTop: 20 }}>
- <ActivityIndicator />
+
+
+ render(){
+
+ if (this .state.isLoading){
+ return (
+ <View style ={{flex: 1 , padding: 20 }}>
+ <ActivityIndicator />
</View >
- );
+ )
}
- return (
- <View style ={{flex: 1 , paddingTop: 20 }}>
- <ListView
- dataSource ={this.state.dataSource}
- renderRow ={(rowData) => <Text > {rowData.title}, {rowData.releaseYear}</Text > }
+ return (
+ <View style ={{flex: 1 , paddingTop:20 }}>
+ <FlatList
+ data ={this.state.dataSource}
+ renderItem ={({item}) => <Text > {item.title}, {item.releaseYear}</Text > }
+ keyExtractor={(item, index) => index}
/>
</View >
);
@@ -103,7 +107,7 @@
-By default, iOS will block any request that's not encrypted using SSL. If you need to fetch from a cleartext URL (one that begins with http) you will first need to add an App Transport Security exception. If you know ahead of time what domains you will need access to, it is more secure to add exceptions just for those domains; if the domains are not known until runtime you can disable ATS completely . Note however that from January 2017, Apple's App Store review will require reasonable justification for disabling ATS . See Apple's documentation for more information.
+By default, iOS will block any request that's not encrypted using SSL. If you need to fetch from a cleartext URL (one that begins with http) you will first need to add an App Transport Security exception . If you know ahead of time what domains you will need access to, it is more secure to add exceptions just for those domains; if the domains are not known until runtime you can disable ATS completely . Note however that from January 2017, Apple's App Store review will require reasonable justification for disabling ATS . See Apple's documentation for more information.
Using Other Networking Libraries
The XMLHttpRequest API is built in to React Native. This means that you can use third party libraries such as frisbee or axios that depend on it, or you can use the XMLHttpRequest API directly if you prefer.
-var request = new XMLHttpRequest();
+var request = new XMLHttpRequest();
request.onreadystatechange = (e ) => {
if (request.readyState !== 4 ) {
return ;
@@ -141,7 +145,7 @@ request.send();
WebSocket Support
React Native also supports WebSockets , a protocol which provides full-duplex communication channels over a single TCP connection.
-var ws = new WebSocket('ws://host.com/path' );
+var ws = new WebSocket('ws://host.com/path' );
ws.onopen = () => {
diff --git a/docs/0.10/performance.html b/docs/0.10/performance.html
index e4f6af97c04..80cb6ef3f1d 100644
--- a/docs/0.10/performance.html
+++ b/docs/0.10/performance.html
@@ -22,7 +22,7 @@
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. Always make sure to test performance in release builds .
Using console.log statements
When running a bundled app, these statements can cause a big bottleneck in the JavaScript thread. This includes calls from debugging libraries such as redux-logger , so make sure to remove them before bundling. You can also use this babel plugin that removes all the console.* calls. You need to install it first with npm i babel-plugin-transform-remove-console --save, and then edit the .babelrc file under your project directory like this:
-{
+{
"env" : {
"production" : {
"plugins" : ["transform-remove-console" ]
@@ -52,7 +52,7 @@
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 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 frames dropped, this may occur. A solution to this is to wrap any action inside of your onPress handler in requestAnimationFrame:
-handleOnPress() {
+handleOnPress() {
this .requestAnimationFrame(() => {
@@ -61,15 +61,17 @@
}
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 at an x-offset of 0. Each frame during this transition, the JavaScript thread needs to send a new x-offset to the main thread. If the JavaScript thread is locked up, it cannot do this and so no update occurs on that frame and the animation stutters.
+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 at an x-offset of
+
+Each frame during this transition, the JavaScript thread needs to send a new x-offset to the main thread. If the JavaScript thread is locked up, it cannot do this and so no update occurs on that frame and the animation stutters.
+
One solution to this is to allow for JavaScript-based animations to be offloaded to the main thread. If we were to do the same thing as in the above example with this approach, we might calculate a list of all x-offsets for the new scene when we are starting the transition and send them to the main thread to execute in an optimized way. Now that the JavaScript thread is freed of this responsibility, it's not a big deal if it drops a few frames while rendering the scene -- you probably won't even notice because you will be too distracted by the pretty transition.
Solving this is one of the main goals behind the new React Navigation library. The views in React Navigation use native components and the Animated library to deliver 60 FPS animations that are run on the native thread.
Profiling
Use the built-in profiler to get detailed information about work done in the JavaScript thread and main thread side-by-side. Access it by selecting Perf Monitor from the Debug menu.
For iOS, Instruments is an invaluable tool, and on Android you should learn to use systrace .
-You can also use react-addons-perf to get insights into where React is spending time when rendering your components.
-Another way to profile JavaScript is to use the Chrome profiler while debugging. This won't give you accurate results as the code is running in Chrome but will give you a general idea of where bottlenecks might be.
But first, make sure that Development Mode is OFF! You should see __DEV__ === false, development-level warning are OFF, performance optimizations are ON in your application logs.
+Another way to profile JavaScript is to use the Chrome profiler while debugging. This won't give you accurate results as the code is running in Chrome but will give you a general idea of where bottlenecks might be. Run the profiler under Chrome's Performance tab. A flame graph will appear under User Timing. To view more details in tabular format, click at the Bottom Up tab below and then select DedicatedWorker Thread at the top left menu.
Profiling Android UI Performance with systrace
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.
@@ -131,7 +133,7 @@
At this point, you'll have some very helpful information to inform your next steps.
Resolving JavaScript 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:
-
+
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 .
Resolving native UI Issues
If you identified a native UI problem, there are usually two scenarios:
@@ -153,7 +155,7 @@
In the second scenario, you'll see something more like this:
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.
+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 an 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.
Unbundling + inline requires
If you have a large app you may want to consider unbundling and using inline requires. This is useful for apps that have a large number of screens which may not ever be opened during a typical usage of the app. Generally it is useful to apps that have large amounts of code that are not needed for a while after startup. For instance the app includes complicated profile screens or lesser used features, but most sessions only involve visiting the main screen of the app for updates. We can optimize the loading of the bundle by using the unbundle feature of the packager and requiring those features and screens inline (when they are actually used).
Loading JavaScript
diff --git a/docs/0.10/running-on-device.html b/docs/0.10/running-on-device.html
index 4c8daafdbeb..d97815e22df 100644
--- a/docs/0.10/running-on-device.html
+++ b/docs/0.10/running-on-device.html
@@ -145,7 +145,7 @@ Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
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
+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.
@@ -188,7 +188,7 @@ emulator-5554 offline
Open the Report navigator tab, select the last Build and search for xip.io. The IP address which gets embedded in the app should match your machines IP address plus the domain .xip.io (e.g. 10.0.1.123.xip.io)
3. Network/router configuration
-React Native uses the wildcard DNS service xip.io to address your device. Some routers have security features to prevent DNS Servers to resolve anything in the local IP range.
+React Native uses the wildcard DNS service xip.io to address your device, as Apple ATS prohibits URLs with IP addresses instead of domain names, and developers' networks are often not set up to resolve local hostnames. Some routers have security features to prevent DNS Servers from resolving to anything in the local IP range.
Now check if you are able to resolve the xip.io address, by running nslookup.
$ nslookup 10.0.1.123.xip.io
@@ -206,7 +206,10 @@ emulator-5554 offline
Run the following in a command prompt:
-$ adb reverse t cp:8081 t cp:8081
+$ adb -s <device name > reverse tcp:8081 tcp:8081
+
+To find the device name, run the following adb command:
+$ adb devices
You can now enable Live reloading from the Developer menu . Your app will reload whenever your JavaScript code has changed.
Method 2: Connect via Wi-Fi
@@ -223,7 +226,7 @@ emulator-5554 offline red screen with an error. This is OK. The following steps will fix that.
Open the in-app Developer menu .
-Go to Dev Settings → Debug server host for device .
+Go to Dev Settings → Debug server host & port for device .
Type in your machine's IP address and the port of the local dev server (e.g. 10.0.1.1:8081).
Go back to the Developer menu and select Reload JS .
@@ -241,7 +244,27 @@ emulator-5554 offline
- 3. Build app for release
+ 3. Configure app to use static bundle
+During the development process, React Native has loaded your JavaScript code dynamically at runtime. For a production build, you want to pre-package the JavaScript bundle and distribute it inside your application. Doing this requires a code change in your code so that it knows to load the static bundle.
+In AppDelegate.m, change the default jsCodeLocation to point to the static bundle that is built in Release.
+ jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle" ];
+
+This will now reference the main.jsbundle resource file that is created during the Bundle React Native code and images Build Phase in Xcode.
+
+Note: The static bundle is built every time you target a physical device, even in Debug. If you want to save time, turn off bundle generation in Debug by adding the following to your shell script in the Xcode Build Phase Bundle React Native code and images:
+
+ if [ "${CONFIGURATION}" == "Debug" ]; then
+ export SKIP_BUNDLING=true
+ fi
+
+ Pro Tip
+As your App Bundle grows in size, you may start to see a white screen flash between your splash screen and the display of your root application view. If this is the case, you can add the following code to AppDelegate.m in order to keep your splash screen displayed during the transition.
+
+ UIView * launchScreenView = [[[NSBundle mainBundle] loadNibNamed:@"LaunchScreen" owner:self options:nil ] objectAtIndex:0 ];
+ launchScreenView.frame = self .window.bounds;
+ rootView.loadingView = launchScreenView;
+
+ 4. Build app for release
You can now build your app for release by tapping ⌘B or selecting Product → Build from the menu bar. Once built for release, you'll be able to distribute the app to beta testers and submit the app to the App Store.
You can also use the React Native CLI to perform this operation using the option --configuration with the value Release (e.g. react-native run-ios --configuration Release).
diff --git a/docs/0.10/signed-apk-android.html b/docs/0.10/signed-apk-android.html
index 38efae62dba..cc3f21ccd61 100644
--- a/docs/0.10/signed-apk-android.html
+++ b/docs/0.10/signed-apk-android.html
@@ -1,10 +1,10 @@
-Generating Signed APK · React Native Android requires that all apps be digitally signed with a certificate before they can be installed, so 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.
+ Android requires that all apps be digitally signed with a certificate before they can be installed, so 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 package the JavaScript bundle.
Generating a signing key
You can generate a private signing key using keytool. On Windows keytool must be run from C:\Program Files\Java\jdkx.x.x_x\bin.
$ keytool -genkey -v -keystore my-release-key.keystore -alias my-key-alias -keyalg RSA -keysize 2048 -validity 10000
@@ -60,6 +60,9 @@ android {
$ cd android && ./gradlew assembleRelease
Gradle's assembleRelease will bundle all the JavaScript needed to run your app into the APK. 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.
+
+Note: Make sure gradle.properties does not include org.gradle.configureondemand=true as that will make release build skip bundling JS and assets into the APK.
+
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. First uninstall any previous version of the app you already have installed. Install it on the device using:
diff --git a/docs/0.10/state.html b/docs/0.10/state.html
index 70088bfa857..940183a382e 100644
--- a/docs/0.10/state.html
+++ b/docs/0.10/state.html
@@ -13,18 +13,18 @@
class Blink extends Component {
constructor (props) {
super (props);
- this .state = {showText : true };
+ this .state = {isShowingText : true };
setInterval(() => {
this .setState(previousState => {
- return { showText : !previousState.showText };
+ return { isShowingText : !previousState.isShowingText };
});
}, 1000 );
}
render() {
- let display = this .state.showText ? this .props.text : ' ' ;
+ let display = this .state.isShowingText ? this .props.text : ' ' ;
return (
<Text > {display}</Text >
);
@@ -46,9 +46,9 @@
// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => BlinkApp);
-
+
-
In a real application, you probably won't be setting state with a timer. You might set state when you have new data arrive from the server, or from user input. You can also use a state container like Redux to control your data flow. In that case you would use Redux to modify your state rather than calling setState directly.
+
In a real application, you probably won't be setting state with a timer. You might set state when you have new data arrive from the server, or from user input. You can also use a state container like Redux to control your data flow. In that case you would use Redux to modify your state rather than calling setState directly.
When setState is called, BlinkApp will re-render its Component. By calling setState within the Timer, the component will re-render every time the Timer ticks.
State works the same way as it does in React, so for more details on handling state, you can look at the React.Component API . At this point, you might be annoyed that most of our examples so far use boring default black text. To make things more beautiful, you will have to learn about Style .
Animations are very important to create a great user experience. Stationary objects must overcome inertia as they start moving. Objects in motion have momentum and rarely come to a stop immediately. Animations allow you to convey physically believable motion in your interface.
-React Native provides two complementary animation systems: Animated for granular and interactive control of specific values, and LayoutAnimation for animated global layout transactions.
+React Native provides two complementary animation systems: Animated for granular and interactive control of specific values, and LayoutAnimation for animated global layout transactions.
Animated API
The Animated API 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 methods to control time-based animation execution.
Animated exports four animatable component types: View, Text, Image, and ScrollView, but you can also create your own using Animated.createAnimatedComponent().
diff --git a/docs/0.11/app-extensions.html b/docs/0.11/app-extensions.html
index 35701b2c477..8e6b2fadea6 100644
--- a/docs/0.11/app-extensions.html
+++ b/docs/0.11/app-extensions.html
@@ -10,7 +10,7 @@
We highly recommend that you watch Conrad Kramer's talk on Memory Use in Extensions to learn more about this topic.
Today widget
The memory limit of a Today widget is 16 MB. As it happens, Today widget implementations using React Native may work unreliably because the memory usage tends to be too high. You can tell if your Today widget is exceeding the memory limit if it yields the message 'Unable to Load':
-
+
Always make sure to test your app extensions in a real device, but be aware that this may not be sufficient, especially when dealing with Today widgets. Debug-configured builds are more likely to exceed the memory limits, while release-configured builds don't fail right away. We highly recommend that you use Xcode's Instruments to analyze your real world memory usage, as it's very likely that your release-configured build is very close to the 16 MB limit. In situations like these, it is easy to go over the 16 MB limit by performing common operations, such as fetching data from an API.
To experiment with the limits of React Native Today widget implementations, try extending the example project in react-native-today-widget .
Other app extensions
diff --git a/docs/0.11/building-for-apple-tv.html b/docs/0.11/building-for-apple-tv.html
index 73d6865a304..a439b4df678 100644
--- a/docs/0.11/building-for-apple-tv.html
+++ b/docs/0.11/building-for-apple-tv.html
@@ -1,10 +1,82 @@
-Building For Apple TV · React Native Apple TV support has been implemented with the intention of making existing React Native iOS applications "just work" on tvOS, with few or no changes needed in the JavaScript code for the applications.
+
+TV devices support has been implemented with the intention of making existing React Native applications "just work" on Apple TV and Android TV, with few or no changes needed in the JavaScript code for the applications.
+
+
+
+ iOS
+
+
+ Android
+
+
+
+
The RNTester app supports Apple TV; use the RNTester-tvOS build target to build for tvOS.
Build changes
@@ -12,10 +84,41 @@
react-native init : New React Native projects created with react-native init will have Apple TV target automatically created in their XCode projects.
JavaScript layer : Support for Apple TV has been added to Platform.ios.js. You can check whether code is running on AppleTV by doing
-var Platform = require ('Platform' );
+var Platform = require ('Platform' );
+var running_on_tv = Platform.isTV;
+
+
+
var running_on_apple_tv = Platform.isTVOS;
+
+ Build changes
+
+Native layer : To run React Native project on Android TV make sure to make the following changes to AndroidManifest.xml
+
+
+ <application
+ ...
+ android:banner ="@drawable/tv_banner"
+ >
+ ...
+ <intent-filter >
+ ...
+
+ <category android:name ="android.intent.category.LEANBACK_LAUNCHER" />
+ </intent-filter >
+ ...
+ </application >
+
+
+JavaScript layer : Support for Android TV has been added to Platform.android.js. You can check whether code is running on Android TV by doing
+
+var Platform = require ('Platform' );
+var running_on_android_tv = Platform.isTV;
+
+
Code changes
+
General support for tvOS : Apple TV specific changes in native code are all wrapped by the TARGET_OS_TV define. These include changes to suppress APIs that are not supported on tvOS (e.g. web views, sliders, switches, status bar, etc.), and changes to support user input from the TV remote or keyboard.
Common codebase : Since tvOS and iOS share most Objective-C and JavaScript code in common, most documentation for iOS applies equally to tvOS.
@@ -25,9 +128,26 @@
touchableHandleActivePressOut will be executed when the touchable view goes out of focus
touchableHandlePress will be executed when the touchable view is actually selected by pressing the "select" button on the TV remote.
-TV remote/keyboard input : A new native class, RCTTVRemoteHandler, sets up gesture recognizers for TV remote events. When TV remote events occur, this class fires notifications that are picked up by RCTTVNavigationEventEmitter (a subclass of RCTEventEmitter), that fires a JS event. This event will be picked up by instances of the TVEventHandler JavaScript object. Application code that needs to implement custom handling of TV remote events can create an instance of TVEventHandler and listen for these events, as in the following code:
-var TVEventHandler = require ('TVEventHandler' );
+
+
+Access to touchable controls : When running on Android TV the Android framework will automatically apply a directional navigation scheme based on relative position of focusable elements in your views. The Touchable mixin has code added to detect focus changes and use existing methods to style the components properly and initiate the proper actions when the view is selected using the TV remote, so TouchableHighlight, TouchableOpacity and TouchableNativeFeedback will "just work". In particular:
+
+touchableHandleActivePressIn will be executed when the touchable view goes into focus
+touchableHandleActivePressOut will be executed when the touchable view goes out of focus
+touchableHandlePress will be executed when the touchable view is actually selected by pressing the "select" button on the TV remote.
+
+
+
+
+TV remote/keyboard input : A new native class, RCTTVRemoteHandler, sets up gesture recognizers for TV remote events. When TV remote events occur, this class fires notifications that are picked up by RCTTVNavigationEventEmitter (a subclass of RCTEventEmitter), that fires a JS event. This event will be picked up by instances of the TVEventHandler JavaScript object. Application code that needs to implement custom handling of TV remote events can create an instance of TVEventHandler and listen for these events, as in the following code:
+
+
+
+TV remote/keyboard input : A new native class, ReactAndroidTVRootViewHelper, sets up key events handlers for TV remote events. When TV remote events occur, this class fires a JS event. This event will be picked up by instances of the TVEventHandler JavaScript object. Application code that needs to implement custom handling of TV remote events can create an instance of TVEventHandler and listen for these events, as in the following code:
+
+
+var TVEventHandler = require ('TVEventHandler' );
.
.
@@ -68,16 +188,115 @@ class Game2048 extends React.Component {
this ._disableTVEventHandler();
}
+
Dev Menu support : On the simulator, cmd-D will bring up the developer menu, just like on iOS. To bring it up on a real Apple TV device, make a long press on the play/pause button on the remote. (Please do not shake the Apple TV device, that will not work :) )
TV remote animations : RCTTVView native code implements Apple-recommended parallax animations to help guide the eye as the user navigates through views. The animations can be disabled or adjusted with new optional view properties.
Back navigation with the TV remote menu button : The BackHandler component, originally written to support the Android back button, now also supports back navigation on the Apple TV using the menu button on the TV remote.
TabBarIOS behavior : The TabBarIOS component wraps the native UITabBar API, which works differently on Apple TV. To avoid jittery rerendering of the tab bar in tvOS (see this issue ), the selected tab bar item can only be set from Javascript on initial render, and is controlled after that by the user through native code.
+
+
+
+Dev Menu support : On the simulator, cmd-M will bring up the developer menu, just like on Android. To bring it up on a real Android TV device, make a long press on the play/pause button on the remote. (Please do not shake the Android TV device, that will not work :) )
+
+
+
Known issues :
ListView scrolling . The issue can be easily worked around by setting removeClippedSubviews to false in ListView and similar components. For more discussion of this issue, see this PR .
+
+
+Known issues :
+
+InputText components do not work for now (i.e. they cannot receive focus).
+
+
+
Headless JS is a way to run tasks in JavaScript while your app is in the background. It can be used, for example, to sync fresh data, handle push notifications, or play music.
The JS API
A task is a simple async function that you register on AppRegistry, similar to registering React applications:
-AppRegistry.registerHeadlessTask('SomeTaskName' , () => require ('SomeTaskName' ));
+AppRegistry.registerHeadlessTask('SomeTaskName' , () => require ('SomeTaskName' ));
Then, in SomeTaskName.js:
-module .exports = async (taskData) => {
+module .exports = async (taskData) => {
};
diff --git a/docs/0.11/height-and-width.html b/docs/0.11/height-and-width.html
index a14d6a40573..84650bd774b 100644
--- a/docs/0.11/height-and-width.html
+++ b/docs/0.11/height-and-width.html
@@ -5,7 +5,7 @@
nav.classList.toggle('docsSliderActive');
};
A component's height and width determine its size on the screen.
- Fixed Dimensions
+ Fixed Dimensions
The simplest way to set the dimensions of a component is by adding a fixed width and height to style. All dimensions in React Native are unitless, and represent density-independent pixels.
import React, { Component } from 'react' ;
import { AppRegistry, View } from 'react-native' ;
@@ -27,7 +27,7 @@ AppRegistry.registerComponent('AwesomeProject', () => FixedDimensionsBasics);
Setting dimensions this way is common for components that should always render at exactly the same size, regardless of screen dimensions.
- Flex Dimensions
+ Flex Dimensions
Use flex in a component's style to have the component expand and shrink dynamically based on available space. Normally you will use flex: 1, which tells a component to fill all available space, shared evenly amongst each other component with the same parent. The larger the flex given, the higher the ratio of space a component will take compared to its siblings.
A component can only expand to fill available space if its parent has dimensions greater than 0. If a parent does not have either a fixed width and height or flex, the parent will have dimensions of 0 and the flex children will not be visible.
diff --git a/docs/0.11/images.html b/docs/0.11/images.html
index 1e5414ef72a..cabb1edb8b9 100644
--- a/docs/0.11/images.html
+++ b/docs/0.11/images.html
@@ -47,8 +47,8 @@ var icon = this.props.active
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.
Static Non-Image Resources
-The require syntax described above can be used to statically include audio, video or document files in your project as well. Most common file types are supported including .mp3, .wav, .mp4, .mov, .html and .pdf. See packager defaults for the full list.
-You can add support for other types by creating a packager config file (see the packager config file for the full list of configuration options).
+The require syntax described above can be used to statically include audio, video or document files in your project as well. Most common file types are supported including .mp3, .wav, .mp4, .mov, .html and .pdf. See packager defaults for the full list.
+You can add support for other types by creating a packager config file (see the packager config file for the full list of configuration options).
A caveat is that videos must use absolute positioning instead of flexGrow, since size info is not currently passed for non-image assets. This limitation doesn't occur for videos that are linked directly into Xcode or the Assets folder for Android.
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.
diff --git a/docs/0.11/improvingux.html b/docs/0.11/improvingux.html
index c1282b2814f..9fb5f15275d 100644
--- a/docs/0.11/improvingux.html
+++ b/docs/0.11/improvingux.html
@@ -18,7 +18,7 @@
Configure text inputs
-Entering text on touch phone is a challange - small screen, software keyboard. But based on what kind of data you need, you can make it easier by properly configuring the text inputs:
+Entering text on touch phone is a challenge - small screen, software keyboard. But based on what kind of data you need, you can make it easier by properly configuring the text inputs:
Focus the first field automatically
Use placeholder text as an example of expected data format
@@ -41,6 +41,8 @@
Android API 21+ uses the material design ripple to provide user with feedback when they touch an interactable area on the screen. React Native exposes this through the TouchableNativeFeedback component . Using this touchable effect instead of opacity or highlight will often make your app feel much more fitting on the platform. That said, you need to be careful when using it because it doesn't work on iOS or on Android API < 21, so you will need to fallback to using one of the other Touchable components on iOS. You can use a library like react-native-platform-touchable to handle the platform differences for you.
Try it on your phone
+ Screen orientation lock
+Unless supporting both, it is considered good practice to lock the screen orientation to either portrait or landscape. On iOS, in the General tab and Deployment Info section of Xcode enable the Device Orientation you want to support (ensure you have selected iPhone from the Devices menu when making the changes). For Android, open the AndroidManifest.xml file and within the activity element add 'android:screenOrientation=”portrait”' to lock to portrait or 'android:screenOrientation=”landscape”' to lock to landscape.
Learn more
Material Design and Human Interface Guidelines are great resources for learning more about designing for mobile platforms.
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 .
+In most cases, React Native will use JavaScriptCore , the JavaScript engine that powers Safari. Note that on iOS, JavaScriptCore does not use JIT due to the absence of writable executable memory in iOS apps.
+When using Chrome debugging, all JavaScript code runs within Chrome itself, communicating with native code via WebSockets. Chrome uses V8 as its JavaScript engine.
-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.
+While both environments are very similar, you may end up hitting some inconsistencies. We're likely going to experiment with other JavaScript 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.
+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
-ES7
+ES8
+Stage 3
+
Specific
-JSX : <View style={{color: 'red'}} />
+JSX : <View style={{color: 'red'}} />
Flow : function foo(x: ?number): string {}
Polyfills
@@ -59,12 +62,16 @@
ES6
ES7
+ES8
+
Specific
diff --git a/docs/0.11/more-resources.html b/docs/0.11/more-resources.html
index d50d56565fb..ab987b43f9b 100644
--- a/docs/0.11/more-resources.html
+++ b/docs/0.11/more-resources.html
@@ -8,16 +8,16 @@
Popular Libraries
If you're using React Native, you probably already know about React . So I feel a bit silly mentioning this. But if you haven't, check out React - it's the best way to build a modern website.
One common question is how to handle the "state" of your React Native application. The most popular library for this is Redux . Don't be afraid of how often Redux uses the word "reducer" - it's a pretty simple library, and there's also a nice series of videos explaining it.
-If you're looking for a library that does a specific thing, check out Awesome React Native , a curated list of components that also has demos, articles, and other stuff. You can also find a curated list of React Native libraries at Native Directory , together with quality assessment, recommendations, a lot of pertinent GitHub information, and code examples.
+If you're looking for a library that does a specific thing, check out Awesome React Native , a curated list of components that also has demos, articles, and other stuff.
Examples
Try out apps from the Showcase to see what React Native is capable of! There are also some example apps on GitHub . You can run the apps on a simulator or device, and you can see the source code for these apps, which is neat.
-The folks who built the app for Facebook's F8 conference in 2016 also open-sourced the code and wrote up a detailed series of tutorials . This is useful if you want a more in-depth example that's more realistic than most sample apps out there.
+The folks who built the app for Facebook's F8 conference also open-sourced the code and wrote up a detailed series of tutorials . This is useful if you want a more in-depth example that's more realistic than most sample apps out there.
Extending React Native
-Looking for a component? JS.coach
Fellow developers write and publish React Native modules to npm and open source them on GitHub.
Making modules helps grow the React Native ecosystem and community. We recommend writing modules for your use cases and sharing them on npm.
Read the guides on Native Modules (iOS , Android ) and Native UI Components (iOS , Android ) if you are interested in extending native functionality.
+Looking for a pre-built component? Check JS.coach .
Development Tools
Nuclide is the IDE that Facebook uses internally for JavaScript development. The killer feature of Nuclide is its debugging ability. It also has great inline Flow support. VS Code is another IDE that is popular with JavaScript developers.
diff --git a/docs/0.11/native-components-android.html b/docs/0.11/native-components-android.html
index 37e316ecf37..ea056aff570 100644
--- a/docs/0.11/native-components-android.html
+++ b/docs/0.11/native-components-android.html
@@ -71,10 +71,10 @@
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.
-
+
import PropTypes from 'prop-types' ;
-import {requireNativeComponent, View} from 'react-native' ;
+import {requireNativeComponent, ViewPropTypes} from 'react-native' ;
var iface = {
name : 'ImageView' ,
@@ -82,7 +82,7 @@
src : PropTypes.string,
borderRadius : PropTypes.number,
resizeMode : PropTypes.oneOf(['cover' , 'contain' , 'stretch' ]),
- ...View.propTypes,
+ ...ViewPropTypes,
},
};
@@ -119,7 +119,7 @@
}
This callback is invoked with the raw event, which we typically process in the wrapper component to make a simpler API:
-
+
class MyCustomView extends React .Component {
constructor (props) {
diff --git a/docs/0.11/native-modules-android.html b/docs/0.11/native-modules-android.html
index dc5ffd6fb3f..947412183ba 100644
--- a/docs/0.11/native-modules-android.html
+++ b/docs/0.11/native-modules-android.html
@@ -107,7 +107,7 @@ ReadableArray -><
}
To make it simpler to access your new functionality from JavaScript, it is common to wrap the native module in a JavaScript module. This is not necessary but saves the consumers of your library the need to pull it off of NativeModules each time. This JavaScript file also becomes a good location for you to add any JavaScript side functionality.
-Mobile apps are rarely made up of a single screen. Managing the presentation of, and transition between, multiple screens is typically handled by what is known as a navigator.
-This guide covers the various navigation components available in React Native. If you are just getting started with navigation, you will probably want to use React Navigation . React Navigation provides an easy to use navigation solution, with the ability to present common stack navigation and tabbed navigation patterns on both iOS and Android. As this is a JavaScript implementation, it provides the greatest amount of configurability as well as flexibility when integrating with state management libraries such as redux .
+This guide covers the various navigation components available in React Native. If you are just getting started with navigation, you will probably want to use React Navigation . React Navigation provides an easy to use navigation solution, with the ability to present common stack navigation and tabbed navigation patterns on both iOS and Android. As this is a JavaScript implementation, it provides the greatest amount of configurability as well as flexibility when integrating with state management libraries such as redux .
If you're only targeting iOS, you may want to also check out NavigatorIOS as a way of providing a native look and feel with minimal configuration, as it provides a wrapper around the native UINavigationController class. This component will not work on Android, however.
If you'd like to achieve a native look and feel on both iOS and Android, or you're integrating React Native into an app that already manages navigation natively, the following libraries provide native navigation on both platforms: native-navigation , react-native-navigation .
React Navigation
@@ -43,10 +43,10 @@ const App = StackNavigator({
React Navigation routers make it easy to override navigation logic or integrate it into redux. Because routers can be nested inside each other, developers can override navigation logic for one area of the app without making widespread changes.
The views in React Navigation use native components and the Animated library to deliver 60fps animations that are run on the native thread. Plus, the animations and gestures can be easily customized.
-For a complete intro to React Navigation, follow the React Navigation Getting Started Guide , or browse other docs such as the Intro to Navigators .
+For a complete intro to React Navigation, follow the React Navigation Getting Started Guide , or browse other docs such as the Intro to Navigators .
NavigatorIOS
NavigatorIOS looks and feels just like UINavigationController , because it is actually built on top of it.
-
+
<NavigatorIOS
initialRoute={{
component : MyScene,
diff --git a/docs/0.11/network.html b/docs/0.11/network.html
index 30927ece9e8..9749bde5a4e 100644
--- a/docs/0.11/network.html
+++ b/docs/0.11/network.html
@@ -9,10 +9,10 @@
React Native provides the Fetch API for your networking needs. Fetch will seem familiar if you have used XMLHttpRequest or other networking APIs before. You may refer to MDN's guide on Using Fetch for additional information.
Making requests
In order to fetch content from an arbitrary URL, just pass the URL to fetch:
-fetch('https://mywebsite.com/mydata.json' );
+fetch('https://mywebsite.com/mydata.json' );
Fetch also takes an optional second argument that allows you to customize the HTTP request. You may want to specify additional headers, or make a POST request:
-fetch('https://mywebsite.com/endpoint/' , {
+fetch('https://mywebsite.com/endpoint/' , {
method : 'POST' ,
headers : {
Accept : 'application/json' ,
@@ -28,7 +28,7 @@
Handling the response
The above examples show how you can make a request. In many cases, you will want to do something with the response.
Networking is an inherently asynchronous operation. Fetch methods will return a Promise that makes it straightforward to write code that works in an asynchronous manner:
-function getMoviesFromApiAsync ( ) {
+function getMoviesFromApiAsync ( ) {
return fetch('https://facebook.github.io/react-native/movies.json' )
.then((response ) => response.json())
.then((responseJson ) => {
@@ -40,7 +40,7 @@
}
You can also use the proposed ES2017 async/await syntax in a React Native app:
-async function getMoviesFromApi ( ) {
+async function getMoviesFromApi ( ) {
try {
let response = await fetch(
'https://facebook.github.io/react-native/movies.json'
@@ -53,48 +53,52 @@
}
Don't forget to catch any errors that may be thrown by fetch, otherwise they will be dropped silently.
-import React, { Component } from 'react' ;
-import { ActivityIndicator, ListView, Text, View } from 'react-native' ;
+import React from 'react' ;
+import { FlatList, ActivityIndicator, Text, View } from 'react-native' ;
-export default class Movies extends Component {
- constructor (props) {
+export default class FetchExample extends React .Component {
+
+ constructor (props){
super (props);
- this .state = {
- isLoading : true
- }
+ this .state ={ isLoading : true }
}
- componentDidMount() {
+ componentDidMount(){
return fetch('https://facebook.github.io/react-native/movies.json' )
.then((response ) => response.json())
.then((responseJson ) => {
- let ds = new ListView.DataSource({rowHasChanged : (r1, r2 ) => r1 !== r2});
+
this .setState({
isLoading : false ,
- dataSource : ds.cloneWithRows(responseJson.movies),
- }, function ( ) {
-
+ dataSource : responseJson.movies,
+ }, function ( ) {
+
});
+
})
- .catch((error ) => {
+ .catch((error ) => {
console .error(error);
});
}
- render() {
- if (this .state.isLoading) {
- return (
- <View style ={{flex: 1 , paddingTop: 20 }}>
- <ActivityIndicator />
+
+
+ render(){
+
+ if (this .state.isLoading){
+ return (
+ <View style ={{flex: 1 , padding: 20 }}>
+ <ActivityIndicator />
</View >
- );
+ )
}
- return (
- <View style ={{flex: 1 , paddingTop: 20 }}>
- <ListView
- dataSource ={this.state.dataSource}
- renderRow ={(rowData) => <Text > {rowData.title}, {rowData.releaseYear}</Text > }
+ return (
+ <View style ={{flex: 1 , paddingTop:20 }}>
+ <FlatList
+ data ={this.state.dataSource}
+ renderItem ={({item}) => <Text > {item.title}, {item.releaseYear}</Text > }
+ keyExtractor={(item, index) => index}
/>
</View >
);
@@ -103,7 +107,7 @@
-By default, iOS will block any request that's not encrypted using SSL. If you need to fetch from a cleartext URL (one that begins with http) you will first need to add an App Transport Security exception. If you know ahead of time what domains you will need access to, it is more secure to add exceptions just for those domains; if the domains are not known until runtime you can disable ATS completely . Note however that from January 2017, Apple's App Store review will require reasonable justification for disabling ATS . See Apple's documentation for more information.
+By default, iOS will block any request that's not encrypted using SSL. If you need to fetch from a cleartext URL (one that begins with http) you will first need to add an App Transport Security exception . If you know ahead of time what domains you will need access to, it is more secure to add exceptions just for those domains; if the domains are not known until runtime you can disable ATS completely . Note however that from January 2017, Apple's App Store review will require reasonable justification for disabling ATS . See Apple's documentation for more information.
Using Other Networking Libraries
The XMLHttpRequest API is built in to React Native. This means that you can use third party libraries such as frisbee or axios that depend on it, or you can use the XMLHttpRequest API directly if you prefer.
-var request = new XMLHttpRequest();
+var request = new XMLHttpRequest();
request.onreadystatechange = (e ) => {
if (request.readyState !== 4 ) {
return ;
@@ -141,7 +145,7 @@ request.send();
WebSocket Support
React Native also supports WebSockets , a protocol which provides full-duplex communication channels over a single TCP connection.
-var ws = new WebSocket('ws://host.com/path' );
+var ws = new WebSocket('ws://host.com/path' );
ws.onopen = () => {
diff --git a/docs/0.11/performance.html b/docs/0.11/performance.html
index 8b9e7b83f79..c43075bc025 100644
--- a/docs/0.11/performance.html
+++ b/docs/0.11/performance.html
@@ -22,7 +22,7 @@
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. Always make sure to test performance in release builds .
Using console.log statements
When running a bundled app, these statements can cause a big bottleneck in the JavaScript thread. This includes calls from debugging libraries such as redux-logger , so make sure to remove them before bundling. You can also use this babel plugin that removes all the console.* calls. You need to install it first with npm i babel-plugin-transform-remove-console --save, and then edit the .babelrc file under your project directory like this:
-{
+{
"env" : {
"production" : {
"plugins" : ["transform-remove-console" ]
@@ -52,7 +52,7 @@
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 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 frames dropped, this may occur. A solution to this is to wrap any action inside of your onPress handler in requestAnimationFrame:
-handleOnPress() {
+handleOnPress() {
this .requestAnimationFrame(() => {
@@ -61,15 +61,17 @@
}
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 at an x-offset of 0. Each frame during this transition, the JavaScript thread needs to send a new x-offset to the main thread. If the JavaScript thread is locked up, it cannot do this and so no update occurs on that frame and the animation stutters.
+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 at an x-offset of
+
+Each frame during this transition, the JavaScript thread needs to send a new x-offset to the main thread. If the JavaScript thread is locked up, it cannot do this and so no update occurs on that frame and the animation stutters.
+
One solution to this is to allow for JavaScript-based animations to be offloaded to the main thread. If we were to do the same thing as in the above example with this approach, we might calculate a list of all x-offsets for the new scene when we are starting the transition and send them to the main thread to execute in an optimized way. Now that the JavaScript thread is freed of this responsibility, it's not a big deal if it drops a few frames while rendering the scene -- you probably won't even notice because you will be too distracted by the pretty transition.
Solving this is one of the main goals behind the new React Navigation library. The views in React Navigation use native components and the Animated library to deliver 60 FPS animations that are run on the native thread.
Profiling
Use the built-in profiler to get detailed information about work done in the JavaScript thread and main thread side-by-side. Access it by selecting Perf Monitor from the Debug menu.
For iOS, Instruments is an invaluable tool, and on Android you should learn to use systrace .
-You can also use react-addons-perf to get insights into where React is spending time when rendering your components.
-Another way to profile JavaScript is to use the Chrome profiler while debugging. This won't give you accurate results as the code is running in Chrome but will give you a general idea of where bottlenecks might be.
But first, make sure that Development Mode is OFF! You should see __DEV__ === false, development-level warning are OFF, performance optimizations are ON in your application logs.
+Another way to profile JavaScript is to use the Chrome profiler while debugging. This won't give you accurate results as the code is running in Chrome but will give you a general idea of where bottlenecks might be. Run the profiler under Chrome's Performance tab. A flame graph will appear under User Timing. To view more details in tabular format, click at the Bottom Up tab below and then select DedicatedWorker Thread at the top left menu.
Profiling Android UI Performance with systrace
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.
@@ -131,7 +133,7 @@
At this point, you'll have some very helpful information to inform your next steps.
Resolving JavaScript 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:
-
+
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 .
Resolving native UI Issues
If you identified a native UI problem, there are usually two scenarios:
@@ -153,7 +155,7 @@
In the second scenario, you'll see something more like this:
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.
+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 an 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.
Unbundling + inline requires
If you have a large app you may want to consider unbundling and using inline requires. This is useful for apps that have a large number of screens which may not ever be opened during a typical usage of the app. Generally it is useful to apps that have large amounts of code that are not needed for a while after startup. For instance the app includes complicated profile screens or lesser used features, but most sessions only involve visiting the main screen of the app for updates. We can optimize the loading of the bundle by using the unbundle feature of the packager and requiring those features and screens inline (when they are actually used).
Loading JavaScript
diff --git a/docs/0.11/running-on-device.html b/docs/0.11/running-on-device.html
index 6c0d97a09f1..dd3bb8fab7c 100644
--- a/docs/0.11/running-on-device.html
+++ b/docs/0.11/running-on-device.html
@@ -145,7 +145,7 @@ Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
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
+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.
@@ -188,7 +188,7 @@ emulator-5554 offline
Open the Report navigator tab, select the last Build and search for xip.io. The IP address which gets embedded in the app should match your machines IP address plus the domain .xip.io (e.g. 10.0.1.123.xip.io)
3. Network/router configuration
-React Native uses the wildcard DNS service xip.io to address your device. Some routers have security features to prevent DNS Servers to resolve anything in the local IP range.
+React Native uses the wildcard DNS service xip.io to address your device, as Apple ATS prohibits URLs with IP addresses instead of domain names, and developers' networks are often not set up to resolve local hostnames. Some routers have security features to prevent DNS Servers from resolving to anything in the local IP range.
Now check if you are able to resolve the xip.io address, by running nslookup.
$ nslookup 10.0.1.123.xip.io
@@ -206,7 +206,10 @@ emulator-5554 offline
Run the following in a command prompt:
-$ adb reverse t cp:8081 t cp:8081
+$ adb -s <device name > reverse tcp:8081 tcp:8081
+
+To find the device name, run the following adb command:
+$ adb devices
You can now enable Live reloading from the Developer menu . Your app will reload whenever your JavaScript code has changed.
Method 2: Connect via Wi-Fi
@@ -223,7 +226,7 @@ emulator-5554 offline red screen with an error. This is OK. The following steps will fix that.
Open the in-app Developer menu .
-Go to Dev Settings → Debug server host for device .
+Go to Dev Settings → Debug server host & port for device .
Type in your machine's IP address and the port of the local dev server (e.g. 10.0.1.1:8081).
Go back to the Developer menu and select Reload JS .
@@ -241,7 +244,27 @@ emulator-5554 offline
- 3. Build app for release
+ 3. Configure app to use static bundle
+During the development process, React Native has loaded your JavaScript code dynamically at runtime. For a production build, you want to pre-package the JavaScript bundle and distribute it inside your application. Doing this requires a code change in your code so that it knows to load the static bundle.
+In AppDelegate.m, change the default jsCodeLocation to point to the static bundle that is built in Release.
+ jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle" ];
+
+This will now reference the main.jsbundle resource file that is created during the Bundle React Native code and images Build Phase in Xcode.
+
+Note: The static bundle is built every time you target a physical device, even in Debug. If you want to save time, turn off bundle generation in Debug by adding the following to your shell script in the Xcode Build Phase Bundle React Native code and images:
+
+ if [ "${CONFIGURATION}" == "Debug" ]; then
+ export SKIP_BUNDLING=true
+ fi
+
+ Pro Tip
+As your App Bundle grows in size, you may start to see a white screen flash between your splash screen and the display of your root application view. If this is the case, you can add the following code to AppDelegate.m in order to keep your splash screen displayed during the transition.
+
+ UIView * launchScreenView = [[[NSBundle mainBundle] loadNibNamed:@"LaunchScreen" owner:self options:nil ] objectAtIndex:0 ];
+ launchScreenView.frame = self .window.bounds;
+ rootView.loadingView = launchScreenView;
+
+ 4. Build app for release
You can now build your app for release by tapping ⌘B or selecting Product → Build from the menu bar. Once built for release, you'll be able to distribute the app to beta testers and submit the app to the App Store.
You can also use the React Native CLI to perform this operation using the option --configuration with the value Release (e.g. react-native run-ios --configuration Release).
diff --git a/docs/0.11/signed-apk-android.html b/docs/0.11/signed-apk-android.html
index daafa7e8497..2970d9c08eb 100644
--- a/docs/0.11/signed-apk-android.html
+++ b/docs/0.11/signed-apk-android.html
@@ -1,10 +1,10 @@
-Generating Signed APK · React Native Android requires that all apps be digitally signed with a certificate before they can be installed, so 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.
+ Android requires that all apps be digitally signed with a certificate before they can be installed, so 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 package the JavaScript bundle.
Generating a signing key
You can generate a private signing key using keytool. On Windows keytool must be run from C:\Program Files\Java\jdkx.x.x_x\bin.
$ keytool -genkey -v -keystore my-release-key.keystore -alias my-key-alias -keyalg RSA -keysize 2048 -validity 10000
@@ -60,6 +60,9 @@ android {
$ cd android && ./gradlew assembleRelease
Gradle's assembleRelease will bundle all the JavaScript needed to run your app into the APK. 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.
+
+Note: Make sure gradle.properties does not include org.gradle.configureondemand=true as that will make release build skip bundling JS and assets into the APK.
+
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. First uninstall any previous version of the app you already have installed. Install it on the device using:
diff --git a/docs/0.11/state.html b/docs/0.11/state.html
index 0a821a93e62..63500d542cf 100644
--- a/docs/0.11/state.html
+++ b/docs/0.11/state.html
@@ -13,18 +13,18 @@
class Blink extends Component {
constructor (props) {
super (props);
- this .state = {showText : true };
+ this .state = {isShowingText : true };
setInterval(() => {
this .setState(previousState => {
- return { showText : !previousState.showText };
+ return { isShowingText : !previousState.isShowingText };
});
}, 1000 );
}
render() {
- let display = this .state.showText ? this .props.text : ' ' ;
+ let display = this .state.isShowingText ? this .props.text : ' ' ;
return (
<Text > {display}</Text >
);
@@ -46,9 +46,9 @@
// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => BlinkApp);
-
+
-
In a real application, you probably won't be setting state with a timer. You might set state when you have new data arrive from the server, or from user input. You can also use a state container like Redux to control your data flow. In that case you would use Redux to modify your state rather than calling setState directly.
+
In a real application, you probably won't be setting state with a timer. You might set state when you have new data arrive from the server, or from user input. You can also use a state container like Redux to control your data flow. In that case you would use Redux to modify your state rather than calling setState directly.
When setState is called, BlinkApp will re-render its Component. By calling setState within the Timer, the component will re-render every time the Timer ticks.
State works the same way as it does in React, so for more details on handling state, you can look at the React.Component API . At this point, you might be annoyed that most of our examples so far use boring default black text. To make things more beautiful, you will have to learn about Style .
Animations are very important to create a great user experience. Stationary objects must overcome inertia as they start moving. Objects in motion have momentum and rarely come to a stop immediately. Animations allow you to convey physically believable motion in your interface.
-React Native provides two complementary animation systems: Animated for granular and interactive control of specific values, and LayoutAnimation for animated global layout transactions.
+React Native provides two complementary animation systems: Animated for granular and interactive control of specific values, and LayoutAnimation for animated global layout transactions.
Animated API
The Animated API 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 methods to control time-based animation execution.
Animated exports four animatable component types: View, Text, Image, and ScrollView, but you can also create your own using Animated.createAnimatedComponent().
diff --git a/docs/0.12/app-extensions.html b/docs/0.12/app-extensions.html
index 36348887e92..18528268589 100644
--- a/docs/0.12/app-extensions.html
+++ b/docs/0.12/app-extensions.html
@@ -10,7 +10,7 @@
We highly recommend that you watch Conrad Kramer's talk on Memory Use in Extensions to learn more about this topic.
Today widget
The memory limit of a Today widget is 16 MB. As it happens, Today widget implementations using React Native may work unreliably because the memory usage tends to be too high. You can tell if your Today widget is exceeding the memory limit if it yields the message 'Unable to Load':
-
+
Always make sure to test your app extensions in a real device, but be aware that this may not be sufficient, especially when dealing with Today widgets. Debug-configured builds are more likely to exceed the memory limits, while release-configured builds don't fail right away. We highly recommend that you use Xcode's Instruments to analyze your real world memory usage, as it's very likely that your release-configured build is very close to the 16 MB limit. In situations like these, it is easy to go over the 16 MB limit by performing common operations, such as fetching data from an API.
To experiment with the limits of React Native Today widget implementations, try extending the example project in react-native-today-widget .
Other app extensions
diff --git a/docs/0.12/building-for-apple-tv.html b/docs/0.12/building-for-apple-tv.html
index 57c12a36fc3..a6b79ece515 100644
--- a/docs/0.12/building-for-apple-tv.html
+++ b/docs/0.12/building-for-apple-tv.html
@@ -1,10 +1,82 @@
-Building For Apple TV · React Native Apple TV support has been implemented with the intention of making existing React Native iOS applications "just work" on tvOS, with few or no changes needed in the JavaScript code for the applications.
+
+TV devices support has been implemented with the intention of making existing React Native applications "just work" on Apple TV and Android TV, with few or no changes needed in the JavaScript code for the applications.
+
+
+
+ iOS
+
+
+ Android
+
+
+
+
The RNTester app supports Apple TV; use the RNTester-tvOS build target to build for tvOS.
Build changes
@@ -12,10 +84,41 @@
react-native init : New React Native projects created with react-native init will have Apple TV target automatically created in their XCode projects.
JavaScript layer : Support for Apple TV has been added to Platform.ios.js. You can check whether code is running on AppleTV by doing
-var Platform = require ('Platform' );
+var Platform = require ('Platform' );
+var running_on_tv = Platform.isTV;
+
+
+
var running_on_apple_tv = Platform.isTVOS;
+
+ Build changes
+
+Native layer : To run React Native project on Android TV make sure to make the following changes to AndroidManifest.xml
+
+
+ <application
+ ...
+ android:banner ="@drawable/tv_banner"
+ >
+ ...
+ <intent-filter >
+ ...
+
+ <category android:name ="android.intent.category.LEANBACK_LAUNCHER" />
+ </intent-filter >
+ ...
+ </application >
+
+
+JavaScript layer : Support for Android TV has been added to Platform.android.js. You can check whether code is running on Android TV by doing
+
+var Platform = require ('Platform' );
+var running_on_android_tv = Platform.isTV;
+
+
Code changes
+
General support for tvOS : Apple TV specific changes in native code are all wrapped by the TARGET_OS_TV define. These include changes to suppress APIs that are not supported on tvOS (e.g. web views, sliders, switches, status bar, etc.), and changes to support user input from the TV remote or keyboard.
Common codebase : Since tvOS and iOS share most Objective-C and JavaScript code in common, most documentation for iOS applies equally to tvOS.
@@ -25,9 +128,26 @@
touchableHandleActivePressOut will be executed when the touchable view goes out of focus
touchableHandlePress will be executed when the touchable view is actually selected by pressing the "select" button on the TV remote.
-TV remote/keyboard input : A new native class, RCTTVRemoteHandler, sets up gesture recognizers for TV remote events. When TV remote events occur, this class fires notifications that are picked up by RCTTVNavigationEventEmitter (a subclass of RCTEventEmitter), that fires a JS event. This event will be picked up by instances of the TVEventHandler JavaScript object. Application code that needs to implement custom handling of TV remote events can create an instance of TVEventHandler and listen for these events, as in the following code:
-var TVEventHandler = require ('TVEventHandler' );
+
+
+Access to touchable controls : When running on Android TV the Android framework will automatically apply a directional navigation scheme based on relative position of focusable elements in your views. The Touchable mixin has code added to detect focus changes and use existing methods to style the components properly and initiate the proper actions when the view is selected using the TV remote, so TouchableHighlight, TouchableOpacity and TouchableNativeFeedback will "just work". In particular:
+
+touchableHandleActivePressIn will be executed when the touchable view goes into focus
+touchableHandleActivePressOut will be executed when the touchable view goes out of focus
+touchableHandlePress will be executed when the touchable view is actually selected by pressing the "select" button on the TV remote.
+
+
+
+
+TV remote/keyboard input : A new native class, RCTTVRemoteHandler, sets up gesture recognizers for TV remote events. When TV remote events occur, this class fires notifications that are picked up by RCTTVNavigationEventEmitter (a subclass of RCTEventEmitter), that fires a JS event. This event will be picked up by instances of the TVEventHandler JavaScript object. Application code that needs to implement custom handling of TV remote events can create an instance of TVEventHandler and listen for these events, as in the following code:
+
+
+
+TV remote/keyboard input : A new native class, ReactAndroidTVRootViewHelper, sets up key events handlers for TV remote events. When TV remote events occur, this class fires a JS event. This event will be picked up by instances of the TVEventHandler JavaScript object. Application code that needs to implement custom handling of TV remote events can create an instance of TVEventHandler and listen for these events, as in the following code:
+
+
+var TVEventHandler = require ('TVEventHandler' );
.
.
@@ -68,16 +188,115 @@ class Game2048 extends React.Component {
this ._disableTVEventHandler();
}
+
Dev Menu support : On the simulator, cmd-D will bring up the developer menu, just like on iOS. To bring it up on a real Apple TV device, make a long press on the play/pause button on the remote. (Please do not shake the Apple TV device, that will not work :) )
TV remote animations : RCTTVView native code implements Apple-recommended parallax animations to help guide the eye as the user navigates through views. The animations can be disabled or adjusted with new optional view properties.
Back navigation with the TV remote menu button : The BackHandler component, originally written to support the Android back button, now also supports back navigation on the Apple TV using the menu button on the TV remote.
TabBarIOS behavior : The TabBarIOS component wraps the native UITabBar API, which works differently on Apple TV. To avoid jittery rerendering of the tab bar in tvOS (see this issue ), the selected tab bar item can only be set from Javascript on initial render, and is controlled after that by the user through native code.
+
+
+
+Dev Menu support : On the simulator, cmd-M will bring up the developer menu, just like on Android. To bring it up on a real Android TV device, make a long press on the play/pause button on the remote. (Please do not shake the Android TV device, that will not work :) )
+
+
+
Known issues :
ListView scrolling . The issue can be easily worked around by setting removeClippedSubviews to false in ListView and similar components. For more discussion of this issue, see this PR .
+
+
+Known issues :
+
+InputText components do not work for now (i.e. they cannot receive focus).
+
+
+
Headless JS is a way to run tasks in JavaScript while your app is in the background. It can be used, for example, to sync fresh data, handle push notifications, or play music.
The JS API
A task is a simple async function that you register on AppRegistry, similar to registering React applications:
-AppRegistry.registerHeadlessTask('SomeTaskName' , () => require ('SomeTaskName' ));
+AppRegistry.registerHeadlessTask('SomeTaskName' , () => require ('SomeTaskName' ));
Then, in SomeTaskName.js:
-module .exports = async (taskData) => {
+module .exports = async (taskData) => {
};
diff --git a/docs/0.12/height-and-width.html b/docs/0.12/height-and-width.html
index 14e434906a9..9c9859082ea 100644
--- a/docs/0.12/height-and-width.html
+++ b/docs/0.12/height-and-width.html
@@ -5,7 +5,7 @@
nav.classList.toggle('docsSliderActive');
};
A component's height and width determine its size on the screen.
- Fixed Dimensions
+ Fixed Dimensions
The simplest way to set the dimensions of a component is by adding a fixed width and height to style. All dimensions in React Native are unitless, and represent density-independent pixels.
import React, { Component } from 'react' ;
import { AppRegistry, View } from 'react-native' ;
@@ -27,7 +27,7 @@ AppRegistry.registerComponent('AwesomeProject', () => FixedDimensionsBasics);
Setting dimensions this way is common for components that should always render at exactly the same size, regardless of screen dimensions.
- Flex Dimensions
+ Flex Dimensions
Use flex in a component's style to have the component expand and shrink dynamically based on available space. Normally you will use flex: 1, which tells a component to fill all available space, shared evenly amongst each other component with the same parent. The larger the flex given, the higher the ratio of space a component will take compared to its siblings.
A component can only expand to fill available space if its parent has dimensions greater than 0. If a parent does not have either a fixed width and height or flex, the parent will have dimensions of 0 and the flex children will not be visible.
diff --git a/docs/0.12/images.html b/docs/0.12/images.html
index 9a827c2fba3..07fa0dd6f3a 100644
--- a/docs/0.12/images.html
+++ b/docs/0.12/images.html
@@ -47,8 +47,8 @@ var icon = this.props.active
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.
Static Non-Image Resources
-The require syntax described above can be used to statically include audio, video or document files in your project as well. Most common file types are supported including .mp3, .wav, .mp4, .mov, .html and .pdf. See packager defaults for the full list.
-You can add support for other types by creating a packager config file (see the packager config file for the full list of configuration options).
+The require syntax described above can be used to statically include audio, video or document files in your project as well. Most common file types are supported including .mp3, .wav, .mp4, .mov, .html and .pdf. See packager defaults for the full list.
+You can add support for other types by creating a packager config file (see the packager config file for the full list of configuration options).
A caveat is that videos must use absolute positioning instead of flexGrow, since size info is not currently passed for non-image assets. This limitation doesn't occur for videos that are linked directly into Xcode or the Assets folder for Android.
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.
diff --git a/docs/0.12/improvingux.html b/docs/0.12/improvingux.html
index 0380507236f..43df6263400 100644
--- a/docs/0.12/improvingux.html
+++ b/docs/0.12/improvingux.html
@@ -18,7 +18,7 @@
Configure text inputs
-Entering text on touch phone is a challange - small screen, software keyboard. But based on what kind of data you need, you can make it easier by properly configuring the text inputs:
+Entering text on touch phone is a challenge - small screen, software keyboard. But based on what kind of data you need, you can make it easier by properly configuring the text inputs:
Focus the first field automatically
Use placeholder text as an example of expected data format
@@ -41,6 +41,8 @@
Android API 21+ uses the material design ripple to provide user with feedback when they touch an interactable area on the screen. React Native exposes this through the TouchableNativeFeedback component . Using this touchable effect instead of opacity or highlight will often make your app feel much more fitting on the platform. That said, you need to be careful when using it because it doesn't work on iOS or on Android API < 21, so you will need to fallback to using one of the other Touchable components on iOS. You can use a library like react-native-platform-touchable to handle the platform differences for you.
Try it on your phone
+ Screen orientation lock
+Unless supporting both, it is considered good practice to lock the screen orientation to either portrait or landscape. On iOS, in the General tab and Deployment Info section of Xcode enable the Device Orientation you want to support (ensure you have selected iPhone from the Devices menu when making the changes). For Android, open the AndroidManifest.xml file and within the activity element add 'android:screenOrientation=”portrait”' to lock to portrait or 'android:screenOrientation=”landscape”' to lock to landscape.
Learn more
Material Design and Human Interface Guidelines are great resources for learning more about designing for mobile platforms.
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 .
+In most cases, React Native will use JavaScriptCore , the JavaScript engine that powers Safari. Note that on iOS, JavaScriptCore does not use JIT due to the absence of writable executable memory in iOS apps.
+When using Chrome debugging, all JavaScript code runs within Chrome itself, communicating with native code via WebSockets. Chrome uses V8 as its JavaScript engine.
-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.
+While both environments are very similar, you may end up hitting some inconsistencies. We're likely going to experiment with other JavaScript 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.
+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
-ES7
+ES8
+Stage 3
+
Specific
-JSX : <View style={{color: 'red'}} />
+JSX : <View style={{color: 'red'}} />
Flow : function foo(x: ?number): string {}
Polyfills
@@ -59,12 +62,16 @@
ES6
ES7
+ES8
+
Specific
diff --git a/docs/0.12/more-resources.html b/docs/0.12/more-resources.html
index 89fff1a66ca..965f17cd973 100644
--- a/docs/0.12/more-resources.html
+++ b/docs/0.12/more-resources.html
@@ -8,16 +8,16 @@
Popular Libraries
If you're using React Native, you probably already know about React . So I feel a bit silly mentioning this. But if you haven't, check out React - it's the best way to build a modern website.
One common question is how to handle the "state" of your React Native application. The most popular library for this is Redux . Don't be afraid of how often Redux uses the word "reducer" - it's a pretty simple library, and there's also a nice series of videos explaining it.
-If you're looking for a library that does a specific thing, check out Awesome React Native , a curated list of components that also has demos, articles, and other stuff. You can also find a curated list of React Native libraries at Native Directory , together with quality assessment, recommendations, a lot of pertinent GitHub information, and code examples.
+If you're looking for a library that does a specific thing, check out Awesome React Native , a curated list of components that also has demos, articles, and other stuff.
Examples
Try out apps from the Showcase to see what React Native is capable of! There are also some example apps on GitHub . You can run the apps on a simulator or device, and you can see the source code for these apps, which is neat.
-The folks who built the app for Facebook's F8 conference in 2016 also open-sourced the code and wrote up a detailed series of tutorials . This is useful if you want a more in-depth example that's more realistic than most sample apps out there.
+The folks who built the app for Facebook's F8 conference also open-sourced the code and wrote up a detailed series of tutorials . This is useful if you want a more in-depth example that's more realistic than most sample apps out there.
Extending React Native
-Looking for a component? JS.coach
Fellow developers write and publish React Native modules to npm and open source them on GitHub.
Making modules helps grow the React Native ecosystem and community. We recommend writing modules for your use cases and sharing them on npm.
Read the guides on Native Modules (iOS , Android ) and Native UI Components (iOS , Android ) if you are interested in extending native functionality.
+Looking for a pre-built component? Check JS.coach .
Development Tools
Nuclide is the IDE that Facebook uses internally for JavaScript development. The killer feature of Nuclide is its debugging ability. It also has great inline Flow support. VS Code is another IDE that is popular with JavaScript developers.
diff --git a/docs/0.12/native-components-android.html b/docs/0.12/native-components-android.html
index 3329eb4471b..dcd38c04604 100644
--- a/docs/0.12/native-components-android.html
+++ b/docs/0.12/native-components-android.html
@@ -71,10 +71,10 @@
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.
-
+
import PropTypes from 'prop-types' ;
-import {requireNativeComponent, View} from 'react-native' ;
+import {requireNativeComponent, ViewPropTypes} from 'react-native' ;
var iface = {
name : 'ImageView' ,
@@ -82,7 +82,7 @@
src : PropTypes.string,
borderRadius : PropTypes.number,
resizeMode : PropTypes.oneOf(['cover' , 'contain' , 'stretch' ]),
- ...View.propTypes,
+ ...ViewPropTypes,
},
};
@@ -119,7 +119,7 @@
}
This callback is invoked with the raw event, which we typically process in the wrapper component to make a simpler API:
-
+
class MyCustomView extends React .Component {
constructor (props) {
diff --git a/docs/0.12/native-modules-android.html b/docs/0.12/native-modules-android.html
index 7eb8ad309e7..a8ffeb62ec8 100644
--- a/docs/0.12/native-modules-android.html
+++ b/docs/0.12/native-modules-android.html
@@ -107,7 +107,7 @@ ReadableArray -><
}
To make it simpler to access your new functionality from JavaScript, it is common to wrap the native module in a JavaScript module. This is not necessary but saves the consumers of your library the need to pull it off of NativeModules each time. This JavaScript file also becomes a good location for you to add any JavaScript side functionality.
-Mobile apps are rarely made up of a single screen. Managing the presentation of, and transition between, multiple screens is typically handled by what is known as a navigator.
-This guide covers the various navigation components available in React Native. If you are just getting started with navigation, you will probably want to use React Navigation . React Navigation provides an easy to use navigation solution, with the ability to present common stack navigation and tabbed navigation patterns on both iOS and Android. As this is a JavaScript implementation, it provides the greatest amount of configurability as well as flexibility when integrating with state management libraries such as redux .
+This guide covers the various navigation components available in React Native. If you are just getting started with navigation, you will probably want to use React Navigation . React Navigation provides an easy to use navigation solution, with the ability to present common stack navigation and tabbed navigation patterns on both iOS and Android. As this is a JavaScript implementation, it provides the greatest amount of configurability as well as flexibility when integrating with state management libraries such as redux .
If you're only targeting iOS, you may want to also check out NavigatorIOS as a way of providing a native look and feel with minimal configuration, as it provides a wrapper around the native UINavigationController class. This component will not work on Android, however.
If you'd like to achieve a native look and feel on both iOS and Android, or you're integrating React Native into an app that already manages navigation natively, the following libraries provide native navigation on both platforms: native-navigation , react-native-navigation .
React Navigation
@@ -43,10 +43,10 @@ const App = StackNavigator({
React Navigation routers make it easy to override navigation logic or integrate it into redux. Because routers can be nested inside each other, developers can override navigation logic for one area of the app without making widespread changes.
The views in React Navigation use native components and the Animated library to deliver 60fps animations that are run on the native thread. Plus, the animations and gestures can be easily customized.
-For a complete intro to React Navigation, follow the React Navigation Getting Started Guide , or browse other docs such as the Intro to Navigators .
+For a complete intro to React Navigation, follow the React Navigation Getting Started Guide , or browse other docs such as the Intro to Navigators .
NavigatorIOS
NavigatorIOS looks and feels just like UINavigationController , because it is actually built on top of it.
-
+
<NavigatorIOS
initialRoute={{
component : MyScene,
diff --git a/docs/0.12/network.html b/docs/0.12/network.html
index e9fe6a4dba4..a8a359eb3e2 100644
--- a/docs/0.12/network.html
+++ b/docs/0.12/network.html
@@ -9,10 +9,10 @@
React Native provides the Fetch API for your networking needs. Fetch will seem familiar if you have used XMLHttpRequest or other networking APIs before. You may refer to MDN's guide on Using Fetch for additional information.
Making requests
In order to fetch content from an arbitrary URL, just pass the URL to fetch:
-fetch('https://mywebsite.com/mydata.json' );
+fetch('https://mywebsite.com/mydata.json' );
Fetch also takes an optional second argument that allows you to customize the HTTP request. You may want to specify additional headers, or make a POST request:
-fetch('https://mywebsite.com/endpoint/' , {
+fetch('https://mywebsite.com/endpoint/' , {
method : 'POST' ,
headers : {
Accept : 'application/json' ,
@@ -28,7 +28,7 @@
Handling the response
The above examples show how you can make a request. In many cases, you will want to do something with the response.
Networking is an inherently asynchronous operation. Fetch methods will return a Promise that makes it straightforward to write code that works in an asynchronous manner:
-function getMoviesFromApiAsync ( ) {
+function getMoviesFromApiAsync ( ) {
return fetch('https://facebook.github.io/react-native/movies.json' )
.then((response ) => response.json())
.then((responseJson ) => {
@@ -40,7 +40,7 @@
}
You can also use the proposed ES2017 async/await syntax in a React Native app:
-async function getMoviesFromApi ( ) {
+async function getMoviesFromApi ( ) {
try {
let response = await fetch(
'https://facebook.github.io/react-native/movies.json'
@@ -53,48 +53,52 @@
}
Don't forget to catch any errors that may be thrown by fetch, otherwise they will be dropped silently.
-import React, { Component } from 'react' ;
-import { ActivityIndicator, ListView, Text, View } from 'react-native' ;
+import React from 'react' ;
+import { FlatList, ActivityIndicator, Text, View } from 'react-native' ;
-export default class Movies extends Component {
- constructor (props) {
+export default class FetchExample extends React .Component {
+
+ constructor (props){
super (props);
- this .state = {
- isLoading : true
- }
+ this .state ={ isLoading : true }
}
- componentDidMount() {
+ componentDidMount(){
return fetch('https://facebook.github.io/react-native/movies.json' )
.then((response ) => response.json())
.then((responseJson ) => {
- let ds = new ListView.DataSource({rowHasChanged : (r1, r2 ) => r1 !== r2});
+
this .setState({
isLoading : false ,
- dataSource : ds.cloneWithRows(responseJson.movies),
- }, function ( ) {
-
+ dataSource : responseJson.movies,
+ }, function ( ) {
+
});
+
})
- .catch((error ) => {
+ .catch((error ) => {
console .error(error);
});
}
- render() {
- if (this .state.isLoading) {
- return (
- <View style ={{flex: 1 , paddingTop: 20 }}>
- <ActivityIndicator />
+
+
+ render(){
+
+ if (this .state.isLoading){
+ return (
+ <View style ={{flex: 1 , padding: 20 }}>
+ <ActivityIndicator />
</View >
- );
+ )
}
- return (
- <View style ={{flex: 1 , paddingTop: 20 }}>
- <ListView
- dataSource ={this.state.dataSource}
- renderRow ={(rowData) => <Text > {rowData.title}, {rowData.releaseYear}</Text > }
+ return (
+ <View style ={{flex: 1 , paddingTop:20 }}>
+ <FlatList
+ data ={this.state.dataSource}
+ renderItem ={({item}) => <Text > {item.title}, {item.releaseYear}</Text > }
+ keyExtractor={(item, index) => index}
/>
</View >
);
@@ -103,7 +107,7 @@
-By default, iOS will block any request that's not encrypted using SSL. If you need to fetch from a cleartext URL (one that begins with http) you will first need to add an App Transport Security exception. If you know ahead of time what domains you will need access to, it is more secure to add exceptions just for those domains; if the domains are not known until runtime you can disable ATS completely . Note however that from January 2017, Apple's App Store review will require reasonable justification for disabling ATS . See Apple's documentation for more information.
+By default, iOS will block any request that's not encrypted using SSL. If you need to fetch from a cleartext URL (one that begins with http) you will first need to add an App Transport Security exception . If you know ahead of time what domains you will need access to, it is more secure to add exceptions just for those domains; if the domains are not known until runtime you can disable ATS completely . Note however that from January 2017, Apple's App Store review will require reasonable justification for disabling ATS . See Apple's documentation for more information.
Using Other Networking Libraries
The XMLHttpRequest API is built in to React Native. This means that you can use third party libraries such as frisbee or axios that depend on it, or you can use the XMLHttpRequest API directly if you prefer.
-var request = new XMLHttpRequest();
+var request = new XMLHttpRequest();
request.onreadystatechange = (e ) => {
if (request.readyState !== 4 ) {
return ;
@@ -141,7 +145,7 @@ request.send();
WebSocket Support
React Native also supports WebSockets , a protocol which provides full-duplex communication channels over a single TCP connection.
-var ws = new WebSocket('ws://host.com/path' );
+var ws = new WebSocket('ws://host.com/path' );
ws.onopen = () => {
diff --git a/docs/0.12/performance.html b/docs/0.12/performance.html
index fa552fa0789..c1f5ac29000 100644
--- a/docs/0.12/performance.html
+++ b/docs/0.12/performance.html
@@ -22,7 +22,7 @@
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. Always make sure to test performance in release builds .
Using console.log statements
When running a bundled app, these statements can cause a big bottleneck in the JavaScript thread. This includes calls from debugging libraries such as redux-logger , so make sure to remove them before bundling. You can also use this babel plugin that removes all the console.* calls. You need to install it first with npm i babel-plugin-transform-remove-console --save, and then edit the .babelrc file under your project directory like this:
-{
+{
"env" : {
"production" : {
"plugins" : ["transform-remove-console" ]
@@ -52,7 +52,7 @@
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 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 frames dropped, this may occur. A solution to this is to wrap any action inside of your onPress handler in requestAnimationFrame:
-handleOnPress() {
+handleOnPress() {
this .requestAnimationFrame(() => {
@@ -61,15 +61,17 @@
}
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 at an x-offset of 0. Each frame during this transition, the JavaScript thread needs to send a new x-offset to the main thread. If the JavaScript thread is locked up, it cannot do this and so no update occurs on that frame and the animation stutters.
+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 at an x-offset of
+
+Each frame during this transition, the JavaScript thread needs to send a new x-offset to the main thread. If the JavaScript thread is locked up, it cannot do this and so no update occurs on that frame and the animation stutters.
+
One solution to this is to allow for JavaScript-based animations to be offloaded to the main thread. If we were to do the same thing as in the above example with this approach, we might calculate a list of all x-offsets for the new scene when we are starting the transition and send them to the main thread to execute in an optimized way. Now that the JavaScript thread is freed of this responsibility, it's not a big deal if it drops a few frames while rendering the scene -- you probably won't even notice because you will be too distracted by the pretty transition.
Solving this is one of the main goals behind the new React Navigation library. The views in React Navigation use native components and the Animated library to deliver 60 FPS animations that are run on the native thread.
Profiling
Use the built-in profiler to get detailed information about work done in the JavaScript thread and main thread side-by-side. Access it by selecting Perf Monitor from the Debug menu.
For iOS, Instruments is an invaluable tool, and on Android you should learn to use systrace .
-You can also use react-addons-perf to get insights into where React is spending time when rendering your components.
-Another way to profile JavaScript is to use the Chrome profiler while debugging. This won't give you accurate results as the code is running in Chrome but will give you a general idea of where bottlenecks might be.
But first, make sure that Development Mode is OFF! You should see __DEV__ === false, development-level warning are OFF, performance optimizations are ON in your application logs.
+Another way to profile JavaScript is to use the Chrome profiler while debugging. This won't give you accurate results as the code is running in Chrome but will give you a general idea of where bottlenecks might be. Run the profiler under Chrome's Performance tab. A flame graph will appear under User Timing. To view more details in tabular format, click at the Bottom Up tab below and then select DedicatedWorker Thread at the top left menu.
Profiling Android UI Performance with systrace
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.
@@ -131,7 +133,7 @@
At this point, you'll have some very helpful information to inform your next steps.
Resolving JavaScript 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:
-
+
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 .
Resolving native UI Issues
If you identified a native UI problem, there are usually two scenarios:
@@ -153,7 +155,7 @@
In the second scenario, you'll see something more like this:
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.
+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 an 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.
Unbundling + inline requires
If you have a large app you may want to consider unbundling and using inline requires. This is useful for apps that have a large number of screens which may not ever be opened during a typical usage of the app. Generally it is useful to apps that have large amounts of code that are not needed for a while after startup. For instance the app includes complicated profile screens or lesser used features, but most sessions only involve visiting the main screen of the app for updates. We can optimize the loading of the bundle by using the unbundle feature of the packager and requiring those features and screens inline (when they are actually used).
Loading JavaScript
diff --git a/docs/0.12/running-on-device.html b/docs/0.12/running-on-device.html
index ae51d9298b0..fd550ca0938 100644
--- a/docs/0.12/running-on-device.html
+++ b/docs/0.12/running-on-device.html
@@ -145,7 +145,7 @@ Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
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
+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.
@@ -188,7 +188,7 @@ emulator-5554 offline
Open the Report navigator tab, select the last Build and search for xip.io. The IP address which gets embedded in the app should match your machines IP address plus the domain .xip.io (e.g. 10.0.1.123.xip.io)
3. Network/router configuration
-React Native uses the wildcard DNS service xip.io to address your device. Some routers have security features to prevent DNS Servers to resolve anything in the local IP range.
+React Native uses the wildcard DNS service xip.io to address your device, as Apple ATS prohibits URLs with IP addresses instead of domain names, and developers' networks are often not set up to resolve local hostnames. Some routers have security features to prevent DNS Servers from resolving to anything in the local IP range.
Now check if you are able to resolve the xip.io address, by running nslookup.
$ nslookup 10.0.1.123.xip.io
@@ -206,7 +206,10 @@ emulator-5554 offline
Run the following in a command prompt:
-$ adb reverse t cp:8081 t cp:8081
+$ adb -s <device name > reverse tcp:8081 tcp:8081
+
+To find the device name, run the following adb command:
+$ adb devices
You can now enable Live reloading from the Developer menu . Your app will reload whenever your JavaScript code has changed.
Method 2: Connect via Wi-Fi
@@ -223,7 +226,7 @@ emulator-5554 offline red screen with an error. This is OK. The following steps will fix that.
Open the in-app Developer menu .
-Go to Dev Settings → Debug server host for device .
+Go to Dev Settings → Debug server host & port for device .
Type in your machine's IP address and the port of the local dev server (e.g. 10.0.1.1:8081).
Go back to the Developer menu and select Reload JS .
@@ -241,7 +244,27 @@ emulator-5554 offline
- 3. Build app for release
+ 3. Configure app to use static bundle
+During the development process, React Native has loaded your JavaScript code dynamically at runtime. For a production build, you want to pre-package the JavaScript bundle and distribute it inside your application. Doing this requires a code change in your code so that it knows to load the static bundle.
+In AppDelegate.m, change the default jsCodeLocation to point to the static bundle that is built in Release.
+ jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle" ];
+
+This will now reference the main.jsbundle resource file that is created during the Bundle React Native code and images Build Phase in Xcode.
+
+Note: The static bundle is built every time you target a physical device, even in Debug. If you want to save time, turn off bundle generation in Debug by adding the following to your shell script in the Xcode Build Phase Bundle React Native code and images:
+
+ if [ "${CONFIGURATION}" == "Debug" ]; then
+ export SKIP_BUNDLING=true
+ fi
+
+ Pro Tip
+As your App Bundle grows in size, you may start to see a white screen flash between your splash screen and the display of your root application view. If this is the case, you can add the following code to AppDelegate.m in order to keep your splash screen displayed during the transition.
+
+ UIView * launchScreenView = [[[NSBundle mainBundle] loadNibNamed:@"LaunchScreen" owner:self options:nil ] objectAtIndex:0 ];
+ launchScreenView.frame = self .window.bounds;
+ rootView.loadingView = launchScreenView;
+
+ 4. Build app for release
You can now build your app for release by tapping ⌘B or selecting Product → Build from the menu bar. Once built for release, you'll be able to distribute the app to beta testers and submit the app to the App Store.
You can also use the React Native CLI to perform this operation using the option --configuration with the value Release (e.g. react-native run-ios --configuration Release).
diff --git a/docs/0.12/signed-apk-android.html b/docs/0.12/signed-apk-android.html
index 5605b344c12..0d193f39e5f 100644
--- a/docs/0.12/signed-apk-android.html
+++ b/docs/0.12/signed-apk-android.html
@@ -1,10 +1,10 @@
-Generating Signed APK · React Native Android requires that all apps be digitally signed with a certificate before they can be installed, so 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.
+ Android requires that all apps be digitally signed with a certificate before they can be installed, so 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 package the JavaScript bundle.
Generating a signing key
You can generate a private signing key using keytool. On Windows keytool must be run from C:\Program Files\Java\jdkx.x.x_x\bin.
$ keytool -genkey -v -keystore my-release-key.keystore -alias my-key-alias -keyalg RSA -keysize 2048 -validity 10000
@@ -60,6 +60,9 @@ android {
$ cd android && ./gradlew assembleRelease
Gradle's assembleRelease will bundle all the JavaScript needed to run your app into the APK. 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.
+
+Note: Make sure gradle.properties does not include org.gradle.configureondemand=true as that will make release build skip bundling JS and assets into the APK.
+
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. First uninstall any previous version of the app you already have installed. Install it on the device using:
diff --git a/docs/0.12/state.html b/docs/0.12/state.html
index 94551a70055..ae7591017a5 100644
--- a/docs/0.12/state.html
+++ b/docs/0.12/state.html
@@ -13,18 +13,18 @@
class Blink extends Component {
constructor (props) {
super (props);
- this .state = {showText : true };
+ this .state = {isShowingText : true };
setInterval(() => {
this .setState(previousState => {
- return { showText : !previousState.showText };
+ return { isShowingText : !previousState.isShowingText };
});
}, 1000 );
}
render() {
- let display = this .state.showText ? this .props.text : ' ' ;
+ let display = this .state.isShowingText ? this .props.text : ' ' ;
return (
<Text > {display}</Text >
);
@@ -46,9 +46,9 @@
// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => BlinkApp);
-
+
-
In a real application, you probably won't be setting state with a timer. You might set state when you have new data arrive from the server, or from user input. You can also use a state container like Redux to control your data flow. In that case you would use Redux to modify your state rather than calling setState directly.
+
In a real application, you probably won't be setting state with a timer. You might set state when you have new data arrive from the server, or from user input. You can also use a state container like Redux to control your data flow. In that case you would use Redux to modify your state rather than calling setState directly.
When setState is called, BlinkApp will re-render its Component. By calling setState within the Timer, the component will re-render every time the Timer ticks.
State works the same way as it does in React, so for more details on handling state, you can look at the React.Component API . At this point, you might be annoyed that most of our examples so far use boring default black text. To make things more beautiful, you will have to learn about Style .
Animations are very important to create a great user experience. Stationary objects must overcome inertia as they start moving. Objects in motion have momentum and rarely come to a stop immediately. Animations allow you to convey physically believable motion in your interface.
-React Native provides two complementary animation systems: Animated for granular and interactive control of specific values, and LayoutAnimation for animated global layout transactions.
+React Native provides two complementary animation systems: Animated for granular and interactive control of specific values, and LayoutAnimation for animated global layout transactions.
Animated API
The Animated API 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 methods to control time-based animation execution.
Animated exports four animatable component types: View, Text, Image, and ScrollView, but you can also create your own using Animated.createAnimatedComponent().
diff --git a/docs/0.13/app-extensions.html b/docs/0.13/app-extensions.html
index 9d24c70f5d7..b9880d9ddcf 100644
--- a/docs/0.13/app-extensions.html
+++ b/docs/0.13/app-extensions.html
@@ -10,7 +10,7 @@
We highly recommend that you watch Conrad Kramer's talk on Memory Use in Extensions to learn more about this topic.
Today widget
The memory limit of a Today widget is 16 MB. As it happens, Today widget implementations using React Native may work unreliably because the memory usage tends to be too high. You can tell if your Today widget is exceeding the memory limit if it yields the message 'Unable to Load':
-
+
Always make sure to test your app extensions in a real device, but be aware that this may not be sufficient, especially when dealing with Today widgets. Debug-configured builds are more likely to exceed the memory limits, while release-configured builds don't fail right away. We highly recommend that you use Xcode's Instruments to analyze your real world memory usage, as it's very likely that your release-configured build is very close to the 16 MB limit. In situations like these, it is easy to go over the 16 MB limit by performing common operations, such as fetching data from an API.
To experiment with the limits of React Native Today widget implementations, try extending the example project in react-native-today-widget .
Other app extensions
diff --git a/docs/0.13/building-for-apple-tv.html b/docs/0.13/building-for-apple-tv.html
index 8cf5c821fdd..1e83d02b13a 100644
--- a/docs/0.13/building-for-apple-tv.html
+++ b/docs/0.13/building-for-apple-tv.html
@@ -1,10 +1,82 @@
-Building For Apple TV · React Native Apple TV support has been implemented with the intention of making existing React Native iOS applications "just work" on tvOS, with few or no changes needed in the JavaScript code for the applications.
+
+TV devices support has been implemented with the intention of making existing React Native applications "just work" on Apple TV and Android TV, with few or no changes needed in the JavaScript code for the applications.
+
+
+
+ iOS
+
+
+ Android
+
+
+
+
The RNTester app supports Apple TV; use the RNTester-tvOS build target to build for tvOS.
Build changes
@@ -12,10 +84,41 @@
react-native init : New React Native projects created with react-native init will have Apple TV target automatically created in their XCode projects.
JavaScript layer : Support for Apple TV has been added to Platform.ios.js. You can check whether code is running on AppleTV by doing
-var Platform = require ('Platform' );
+var Platform = require ('Platform' );
+var running_on_tv = Platform.isTV;
+
+
+
var running_on_apple_tv = Platform.isTVOS;
+
+ Build changes
+
+Native layer : To run React Native project on Android TV make sure to make the following changes to AndroidManifest.xml
+
+
+ <application
+ ...
+ android:banner ="@drawable/tv_banner"
+ >
+ ...
+ <intent-filter >
+ ...
+
+ <category android:name ="android.intent.category.LEANBACK_LAUNCHER" />
+ </intent-filter >
+ ...
+ </application >
+
+
+JavaScript layer : Support for Android TV has been added to Platform.android.js. You can check whether code is running on Android TV by doing
+
+var Platform = require ('Platform' );
+var running_on_android_tv = Platform.isTV;
+
+
Code changes
+
General support for tvOS : Apple TV specific changes in native code are all wrapped by the TARGET_OS_TV define. These include changes to suppress APIs that are not supported on tvOS (e.g. web views, sliders, switches, status bar, etc.), and changes to support user input from the TV remote or keyboard.
Common codebase : Since tvOS and iOS share most Objective-C and JavaScript code in common, most documentation for iOS applies equally to tvOS.
@@ -25,9 +128,26 @@
touchableHandleActivePressOut will be executed when the touchable view goes out of focus
touchableHandlePress will be executed when the touchable view is actually selected by pressing the "select" button on the TV remote.
-TV remote/keyboard input : A new native class, RCTTVRemoteHandler, sets up gesture recognizers for TV remote events. When TV remote events occur, this class fires notifications that are picked up by RCTTVNavigationEventEmitter (a subclass of RCTEventEmitter), that fires a JS event. This event will be picked up by instances of the TVEventHandler JavaScript object. Application code that needs to implement custom handling of TV remote events can create an instance of TVEventHandler and listen for these events, as in the following code:
-var TVEventHandler = require ('TVEventHandler' );
+
+
+Access to touchable controls : When running on Android TV the Android framework will automatically apply a directional navigation scheme based on relative position of focusable elements in your views. The Touchable mixin has code added to detect focus changes and use existing methods to style the components properly and initiate the proper actions when the view is selected using the TV remote, so TouchableHighlight, TouchableOpacity and TouchableNativeFeedback will "just work". In particular:
+
+touchableHandleActivePressIn will be executed when the touchable view goes into focus
+touchableHandleActivePressOut will be executed when the touchable view goes out of focus
+touchableHandlePress will be executed when the touchable view is actually selected by pressing the "select" button on the TV remote.
+
+
+
+
+TV remote/keyboard input : A new native class, RCTTVRemoteHandler, sets up gesture recognizers for TV remote events. When TV remote events occur, this class fires notifications that are picked up by RCTTVNavigationEventEmitter (a subclass of RCTEventEmitter), that fires a JS event. This event will be picked up by instances of the TVEventHandler JavaScript object. Application code that needs to implement custom handling of TV remote events can create an instance of TVEventHandler and listen for these events, as in the following code:
+
+
+
+TV remote/keyboard input : A new native class, ReactAndroidTVRootViewHelper, sets up key events handlers for TV remote events. When TV remote events occur, this class fires a JS event. This event will be picked up by instances of the TVEventHandler JavaScript object. Application code that needs to implement custom handling of TV remote events can create an instance of TVEventHandler and listen for these events, as in the following code:
+
+
+var TVEventHandler = require ('TVEventHandler' );
.
.
@@ -68,16 +188,115 @@ class Game2048 extends React.Component {
this ._disableTVEventHandler();
}
+
Dev Menu support : On the simulator, cmd-D will bring up the developer menu, just like on iOS. To bring it up on a real Apple TV device, make a long press on the play/pause button on the remote. (Please do not shake the Apple TV device, that will not work :) )
TV remote animations : RCTTVView native code implements Apple-recommended parallax animations to help guide the eye as the user navigates through views. The animations can be disabled or adjusted with new optional view properties.
Back navigation with the TV remote menu button : The BackHandler component, originally written to support the Android back button, now also supports back navigation on the Apple TV using the menu button on the TV remote.
TabBarIOS behavior : The TabBarIOS component wraps the native UITabBar API, which works differently on Apple TV. To avoid jittery rerendering of the tab bar in tvOS (see this issue ), the selected tab bar item can only be set from Javascript on initial render, and is controlled after that by the user through native code.
+
+
+
+Dev Menu support : On the simulator, cmd-M will bring up the developer menu, just like on Android. To bring it up on a real Android TV device, make a long press on the play/pause button on the remote. (Please do not shake the Android TV device, that will not work :) )
+
+
+
Known issues :
ListView scrolling . The issue can be easily worked around by setting removeClippedSubviews to false in ListView and similar components. For more discussion of this issue, see this PR .
+
+
+Known issues :
+
+InputText components do not work for now (i.e. they cannot receive focus).
+
+
+
Headless JS is a way to run tasks in JavaScript while your app is in the background. It can be used, for example, to sync fresh data, handle push notifications, or play music.
The JS API
A task is a simple async function that you register on AppRegistry, similar to registering React applications:
-AppRegistry.registerHeadlessTask('SomeTaskName' , () => require ('SomeTaskName' ));
+AppRegistry.registerHeadlessTask('SomeTaskName' , () => require ('SomeTaskName' ));
Then, in SomeTaskName.js:
-module .exports = async (taskData) => {
+module .exports = async (taskData) => {
};
diff --git a/docs/0.13/height-and-width.html b/docs/0.13/height-and-width.html
index 70773c22b61..2ff2102af59 100644
--- a/docs/0.13/height-and-width.html
+++ b/docs/0.13/height-and-width.html
@@ -5,7 +5,7 @@
nav.classList.toggle('docsSliderActive');
};
A component's height and width determine its size on the screen.
- Fixed Dimensions
+ Fixed Dimensions
The simplest way to set the dimensions of a component is by adding a fixed width and height to style. All dimensions in React Native are unitless, and represent density-independent pixels.
import React, { Component } from 'react' ;
import { AppRegistry, View } from 'react-native' ;
@@ -27,7 +27,7 @@ AppRegistry.registerComponent('AwesomeProject', () => FixedDimensionsBasics);
Setting dimensions this way is common for components that should always render at exactly the same size, regardless of screen dimensions.
- Flex Dimensions
+ Flex Dimensions
Use flex in a component's style to have the component expand and shrink dynamically based on available space. Normally you will use flex: 1, which tells a component to fill all available space, shared evenly amongst each other component with the same parent. The larger the flex given, the higher the ratio of space a component will take compared to its siblings.
A component can only expand to fill available space if its parent has dimensions greater than 0. If a parent does not have either a fixed width and height or flex, the parent will have dimensions of 0 and the flex children will not be visible.
diff --git a/docs/0.13/images.html b/docs/0.13/images.html
index 7b5b532e75b..6bc444217f0 100644
--- a/docs/0.13/images.html
+++ b/docs/0.13/images.html
@@ -47,8 +47,8 @@ var icon = this.props.active
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.
Static Non-Image Resources
-The require syntax described above can be used to statically include audio, video or document files in your project as well. Most common file types are supported including .mp3, .wav, .mp4, .mov, .html and .pdf. See packager defaults for the full list.
-You can add support for other types by creating a packager config file (see the packager config file for the full list of configuration options).
+The require syntax described above can be used to statically include audio, video or document files in your project as well. Most common file types are supported including .mp3, .wav, .mp4, .mov, .html and .pdf. See packager defaults for the full list.
+You can add support for other types by creating a packager config file (see the packager config file for the full list of configuration options).
A caveat is that videos must use absolute positioning instead of flexGrow, since size info is not currently passed for non-image assets. This limitation doesn't occur for videos that are linked directly into Xcode or the Assets folder for Android.
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.
diff --git a/docs/0.13/improvingux.html b/docs/0.13/improvingux.html
index a7a4650f449..3134e25a367 100644
--- a/docs/0.13/improvingux.html
+++ b/docs/0.13/improvingux.html
@@ -18,7 +18,7 @@
Configure text inputs
-Entering text on touch phone is a challange - small screen, software keyboard. But based on what kind of data you need, you can make it easier by properly configuring the text inputs:
+Entering text on touch phone is a challenge - small screen, software keyboard. But based on what kind of data you need, you can make it easier by properly configuring the text inputs:
Focus the first field automatically
Use placeholder text as an example of expected data format
@@ -41,6 +41,8 @@
Android API 21+ uses the material design ripple to provide user with feedback when they touch an interactable area on the screen. React Native exposes this through the TouchableNativeFeedback component . Using this touchable effect instead of opacity or highlight will often make your app feel much more fitting on the platform. That said, you need to be careful when using it because it doesn't work on iOS or on Android API < 21, so you will need to fallback to using one of the other Touchable components on iOS. You can use a library like react-native-platform-touchable to handle the platform differences for you.
Try it on your phone
+ Screen orientation lock
+Unless supporting both, it is considered good practice to lock the screen orientation to either portrait or landscape. On iOS, in the General tab and Deployment Info section of Xcode enable the Device Orientation you want to support (ensure you have selected iPhone from the Devices menu when making the changes). For Android, open the AndroidManifest.xml file and within the activity element add 'android:screenOrientation=”portrait”' to lock to portrait or 'android:screenOrientation=”landscape”' to lock to landscape.
Learn more
Material Design and Human Interface Guidelines are great resources for learning more about designing for mobile platforms.
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 .
+In most cases, React Native will use JavaScriptCore , the JavaScript engine that powers Safari. Note that on iOS, JavaScriptCore does not use JIT due to the absence of writable executable memory in iOS apps.
+When using Chrome debugging, all JavaScript code runs within Chrome itself, communicating with native code via WebSockets. Chrome uses V8 as its JavaScript engine.
-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.
+While both environments are very similar, you may end up hitting some inconsistencies. We're likely going to experiment with other JavaScript 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.
+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
-ES7
+ES8
+Stage 3
+
Specific
-JSX : <View style={{color: 'red'}} />
+JSX : <View style={{color: 'red'}} />
Flow : function foo(x: ?number): string {}
Polyfills
@@ -59,12 +62,16 @@
ES6
ES7
+ES8
+
Specific
diff --git a/docs/0.13/more-resources.html b/docs/0.13/more-resources.html
index 4f62ec3a4cd..3d98799c33c 100644
--- a/docs/0.13/more-resources.html
+++ b/docs/0.13/more-resources.html
@@ -8,16 +8,16 @@
Popular Libraries
If you're using React Native, you probably already know about React . So I feel a bit silly mentioning this. But if you haven't, check out React - it's the best way to build a modern website.
One common question is how to handle the "state" of your React Native application. The most popular library for this is Redux . Don't be afraid of how often Redux uses the word "reducer" - it's a pretty simple library, and there's also a nice series of videos explaining it.
-If you're looking for a library that does a specific thing, check out Awesome React Native , a curated list of components that also has demos, articles, and other stuff. You can also find a curated list of React Native libraries at Native Directory , together with quality assessment, recommendations, a lot of pertinent GitHub information, and code examples.
+If you're looking for a library that does a specific thing, check out Awesome React Native , a curated list of components that also has demos, articles, and other stuff.
Examples
Try out apps from the Showcase to see what React Native is capable of! There are also some example apps on GitHub . You can run the apps on a simulator or device, and you can see the source code for these apps, which is neat.
-The folks who built the app for Facebook's F8 conference in 2016 also open-sourced the code and wrote up a detailed series of tutorials . This is useful if you want a more in-depth example that's more realistic than most sample apps out there.
+The folks who built the app for Facebook's F8 conference also open-sourced the code and wrote up a detailed series of tutorials . This is useful if you want a more in-depth example that's more realistic than most sample apps out there.
Extending React Native
-Looking for a component? JS.coach
Fellow developers write and publish React Native modules to npm and open source them on GitHub.
Making modules helps grow the React Native ecosystem and community. We recommend writing modules for your use cases and sharing them on npm.
Read the guides on Native Modules (iOS , Android ) and Native UI Components (iOS , Android ) if you are interested in extending native functionality.
+Looking for a pre-built component? Check JS.coach .
Development Tools
Nuclide is the IDE that Facebook uses internally for JavaScript development. The killer feature of Nuclide is its debugging ability. It also has great inline Flow support. VS Code is another IDE that is popular with JavaScript developers.
diff --git a/docs/0.13/native-components-android.html b/docs/0.13/native-components-android.html
index c7487eb3dee..f04e0f3b213 100644
--- a/docs/0.13/native-components-android.html
+++ b/docs/0.13/native-components-android.html
@@ -71,10 +71,10 @@
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.
-
+
import PropTypes from 'prop-types' ;
-import {requireNativeComponent, View} from 'react-native' ;
+import {requireNativeComponent, ViewPropTypes} from 'react-native' ;
var iface = {
name : 'ImageView' ,
@@ -82,7 +82,7 @@
src : PropTypes.string,
borderRadius : PropTypes.number,
resizeMode : PropTypes.oneOf(['cover' , 'contain' , 'stretch' ]),
- ...View.propTypes,
+ ...ViewPropTypes,
},
};
@@ -119,7 +119,7 @@
}
This callback is invoked with the raw event, which we typically process in the wrapper component to make a simpler API:
-
+
class MyCustomView extends React .Component {
constructor (props) {
diff --git a/docs/0.13/native-modules-android.html b/docs/0.13/native-modules-android.html
index 8a57709aa9a..dd470fd6114 100644
--- a/docs/0.13/native-modules-android.html
+++ b/docs/0.13/native-modules-android.html
@@ -107,7 +107,7 @@ ReadableArray -><
}
To make it simpler to access your new functionality from JavaScript, it is common to wrap the native module in a JavaScript module. This is not necessary but saves the consumers of your library the need to pull it off of NativeModules each time. This JavaScript file also becomes a good location for you to add any JavaScript side functionality.
-Mobile apps are rarely made up of a single screen. Managing the presentation of, and transition between, multiple screens is typically handled by what is known as a navigator.
-This guide covers the various navigation components available in React Native. If you are just getting started with navigation, you will probably want to use React Navigation . React Navigation provides an easy to use navigation solution, with the ability to present common stack navigation and tabbed navigation patterns on both iOS and Android. As this is a JavaScript implementation, it provides the greatest amount of configurability as well as flexibility when integrating with state management libraries such as redux .
+This guide covers the various navigation components available in React Native. If you are just getting started with navigation, you will probably want to use React Navigation . React Navigation provides an easy to use navigation solution, with the ability to present common stack navigation and tabbed navigation patterns on both iOS and Android. As this is a JavaScript implementation, it provides the greatest amount of configurability as well as flexibility when integrating with state management libraries such as redux .
If you're only targeting iOS, you may want to also check out NavigatorIOS as a way of providing a native look and feel with minimal configuration, as it provides a wrapper around the native UINavigationController class. This component will not work on Android, however.
If you'd like to achieve a native look and feel on both iOS and Android, or you're integrating React Native into an app that already manages navigation natively, the following libraries provide native navigation on both platforms: native-navigation , react-native-navigation .
React Navigation
@@ -43,10 +43,10 @@ const App = StackNavigator({
React Navigation routers make it easy to override navigation logic or integrate it into redux. Because routers can be nested inside each other, developers can override navigation logic for one area of the app without making widespread changes.
The views in React Navigation use native components and the Animated library to deliver 60fps animations that are run on the native thread. Plus, the animations and gestures can be easily customized.
-For a complete intro to React Navigation, follow the React Navigation Getting Started Guide , or browse other docs such as the Intro to Navigators .
+For a complete intro to React Navigation, follow the React Navigation Getting Started Guide , or browse other docs such as the Intro to Navigators .
NavigatorIOS
NavigatorIOS looks and feels just like UINavigationController , because it is actually built on top of it.
-
+
<NavigatorIOS
initialRoute={{
component : MyScene,
diff --git a/docs/0.13/network.html b/docs/0.13/network.html
index c8e59052885..afe43350e2f 100644
--- a/docs/0.13/network.html
+++ b/docs/0.13/network.html
@@ -9,10 +9,10 @@
React Native provides the Fetch API for your networking needs. Fetch will seem familiar if you have used XMLHttpRequest or other networking APIs before. You may refer to MDN's guide on Using Fetch for additional information.
Making requests
In order to fetch content from an arbitrary URL, just pass the URL to fetch:
-fetch('https://mywebsite.com/mydata.json' );
+fetch('https://mywebsite.com/mydata.json' );
Fetch also takes an optional second argument that allows you to customize the HTTP request. You may want to specify additional headers, or make a POST request:
-fetch('https://mywebsite.com/endpoint/' , {
+fetch('https://mywebsite.com/endpoint/' , {
method : 'POST' ,
headers : {
Accept : 'application/json' ,
@@ -28,7 +28,7 @@
Handling the response
The above examples show how you can make a request. In many cases, you will want to do something with the response.
Networking is an inherently asynchronous operation. Fetch methods will return a Promise that makes it straightforward to write code that works in an asynchronous manner:
-function getMoviesFromApiAsync ( ) {
+function getMoviesFromApiAsync ( ) {
return fetch('https://facebook.github.io/react-native/movies.json' )
.then((response ) => response.json())
.then((responseJson ) => {
@@ -40,7 +40,7 @@
}
You can also use the proposed ES2017 async/await syntax in a React Native app:
-async function getMoviesFromApi ( ) {
+async function getMoviesFromApi ( ) {
try {
let response = await fetch(
'https://facebook.github.io/react-native/movies.json'
@@ -53,48 +53,52 @@
}
Don't forget to catch any errors that may be thrown by fetch, otherwise they will be dropped silently.
-import React, { Component } from 'react' ;
-import { ActivityIndicator, ListView, Text, View } from 'react-native' ;
+import React from 'react' ;
+import { FlatList, ActivityIndicator, Text, View } from 'react-native' ;
-export default class Movies extends Component {
- constructor (props) {
+export default class FetchExample extends React .Component {
+
+ constructor (props){
super (props);
- this .state = {
- isLoading : true
- }
+ this .state ={ isLoading : true }
}
- componentDidMount() {
+ componentDidMount(){
return fetch('https://facebook.github.io/react-native/movies.json' )
.then((response ) => response.json())
.then((responseJson ) => {
- let ds = new ListView.DataSource({rowHasChanged : (r1, r2 ) => r1 !== r2});
+
this .setState({
isLoading : false ,
- dataSource : ds.cloneWithRows(responseJson.movies),
- }, function ( ) {
-
+ dataSource : responseJson.movies,
+ }, function ( ) {
+
});
+
})
- .catch((error ) => {
+ .catch((error ) => {
console .error(error);
});
}
- render() {
- if (this .state.isLoading) {
- return (
- <View style ={{flex: 1 , paddingTop: 20 }}>
- <ActivityIndicator />
+
+
+ render(){
+
+ if (this .state.isLoading){
+ return (
+ <View style ={{flex: 1 , padding: 20 }}>
+ <ActivityIndicator />
</View >
- );
+ )
}
- return (
- <View style ={{flex: 1 , paddingTop: 20 }}>
- <ListView
- dataSource ={this.state.dataSource}
- renderRow ={(rowData) => <Text > {rowData.title}, {rowData.releaseYear}</Text > }
+ return (
+ <View style ={{flex: 1 , paddingTop:20 }}>
+ <FlatList
+ data ={this.state.dataSource}
+ renderItem ={({item}) => <Text > {item.title}, {item.releaseYear}</Text > }
+ keyExtractor={(item, index) => index}
/>
</View >
);
@@ -103,7 +107,7 @@
-By default, iOS will block any request that's not encrypted using SSL. If you need to fetch from a cleartext URL (one that begins with http) you will first need to add an App Transport Security exception. If you know ahead of time what domains you will need access to, it is more secure to add exceptions just for those domains; if the domains are not known until runtime you can disable ATS completely . Note however that from January 2017, Apple's App Store review will require reasonable justification for disabling ATS . See Apple's documentation for more information.
+By default, iOS will block any request that's not encrypted using SSL. If you need to fetch from a cleartext URL (one that begins with http) you will first need to add an App Transport Security exception . If you know ahead of time what domains you will need access to, it is more secure to add exceptions just for those domains; if the domains are not known until runtime you can disable ATS completely . Note however that from January 2017, Apple's App Store review will require reasonable justification for disabling ATS . See Apple's documentation for more information.
Using Other Networking Libraries
The XMLHttpRequest API is built in to React Native. This means that you can use third party libraries such as frisbee or axios that depend on it, or you can use the XMLHttpRequest API directly if you prefer.
-var request = new XMLHttpRequest();
+var request = new XMLHttpRequest();
request.onreadystatechange = (e ) => {
if (request.readyState !== 4 ) {
return ;
@@ -141,7 +145,7 @@ request.send();
WebSocket Support
React Native also supports WebSockets , a protocol which provides full-duplex communication channels over a single TCP connection.
-var ws = new WebSocket('ws://host.com/path' );
+var ws = new WebSocket('ws://host.com/path' );
ws.onopen = () => {
diff --git a/docs/0.13/performance.html b/docs/0.13/performance.html
index 807f4328d4f..5fd6f0864da 100644
--- a/docs/0.13/performance.html
+++ b/docs/0.13/performance.html
@@ -22,7 +22,7 @@
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. Always make sure to test performance in release builds .
Using console.log statements
When running a bundled app, these statements can cause a big bottleneck in the JavaScript thread. This includes calls from debugging libraries such as redux-logger , so make sure to remove them before bundling. You can also use this babel plugin that removes all the console.* calls. You need to install it first with npm i babel-plugin-transform-remove-console --save, and then edit the .babelrc file under your project directory like this:
-{
+{
"env" : {
"production" : {
"plugins" : ["transform-remove-console" ]
@@ -52,7 +52,7 @@
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.