diff --git a/docs/accessibility.html b/docs/accessibility.html index bfd11075fee..bc7b5ac3a42 100644 --- a/docs/accessibility.html +++ b/docs/accessibility.html @@ -1,4 +1,4 @@ -
Both iOS and Android provide APIs for making apps accessible to people with disabilities. In addition, both platforms provide bundled assistive technologies, like the screen readers VoiceOver (iOS) and TalkBack (Android) for the visually impaired. Similarly, in React Native we have included APIs designed to provide developers with support for making apps more accessible. Take note, iOS and Android differ slightly in their approaches, and thus the React Native implementations may vary by platform.
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}’.
Both iOS and Android provide APIs for making apps accessible to people with disabilities. In addition, both platforms provide bundled assistive technologies, like the screen readers VoiceOver (iOS) and TalkBack (Android) for the visually impaired. Similarly, in React Native we have included APIs designed to provide developers with support for making apps more accessible. Take note, iOS and Android differ slightly in their approaches, and thus the React Native implementations may vary by platform.
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}’.
In the above example, we can't get accessibility focus separately on 'text one' and 'text two'. Instead we get focus on a parent view with 'accessible' property.
When a view is marked as accessible, it is a good practice to set an accessibilityLabel on the view, so that people who use VoiceOver know what element they have selected. VoiceOver will read this string when a user selects the associated element.
To use, set the accessibilityLabel property to a custom string on your View:
In the above example we've created a custom radio button that now behaves like a native one. More specifically, TalkBack now correctly announces changes to the radio button selection.
To enable VoiceOver, go to the Settings app on your iOS device. Tap General, then Accessibility. There you will find many tools that people use to use to make their devices more usable, such as bolder text, increased contrast, and VoiceOver.
To enable VoiceOver, tap on VoiceOver under "Vision" and toggle the switch that appears at the top.
At the very bottom of the Accessibility settings, there is an "Accessibility Shortcut". You can use this to toggle VoiceOver by triple clicking the Home button.
You can edit the content above on GitHub and send us a pull request!
Display an iOS action sheet. The options object must contain one or more
+
Display an iOS action sheet. The options object must contain one or more
of:
options (array of strings) - a list of button titles (required)cancelButtonIndex (int) - index of cancel button in optionsdestructiveButtonIndex (int) - index of destructive button in optionstitle (string) - a title to show above the action sheetmessage (string) - a message to show below the titleDisplay the iOS share sheet. The options object should contain
one or both of message and url and can additionally have
a subject or excludedActivityTypes:
url (string) - a URL to sharemessage (string) - a message to sharesubject (string) - a subject for the messageexcludedActivityTypes (array) - the activities to exclude from the ActionSheetNOTE: if url points to a local file, or is a base64-encoded
@@ -204,7 +204,7 @@ exports.examples return <ShareScreenshotExample />;
}
}
-];
Displays a circular loading indicator.
Whether to show the indicator (true, the default) or hide it (false).
Size of the indicator (default is 'small'). +
Displays a circular loading indicator.
Whether to show the indicator (true, the default) or hide it (false).
Size of the indicator (default is 'small'). Passing a number to the size prop is only supported on Android.
Whether the indicator should hide when not animating (true by default).
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
Launches an alert dialog with the specified title and message.
Optionally provide a list of buttons. Tapping any button will fire the +
Launches an alert dialog with the specified title and message.
Optionally provide a list of buttons. Tapping any button will fire the respective onPress callback and dismiss the alert. By default, the only button will be an 'OK' button.
This is an API that works both on iOS and Android and can show static alerts. To show an alert that prompts the user to enter some information, @@ -148,7 +148,7 @@ class AlertExample extends .exports = { AlertExample, SimpleAlertExampleBlock, -};
AlertIOS provides functionality to create an iOS alert dialog with a
+
AlertIOS provides functionality to create an iOS alert dialog with a
message or create a prompt for user input.
Creating an iOS alert:
You will need to build React Native from source if you want to work on a new feature/bug fix, try out the latest features which are not released yet, or maintain your own fork with patches that cannot be merged to the core.
Assuming you have the Android SDK installed, run android to open the Android SDK Manager.
Make sure you have the following installed:
build.gradle)build.gradle)Android Support Repository) >= 17 (for Android Support Library)Step 1: Set environment variables through your local shell.
Note: Files may vary based on shell flavor. See below for examples from common shells.
.bash_profile or .bashrc.zprofile or .zshrc.profile or $ENVExample:
You will need to build React Native from source if you want to work on a new feature/bug fix, try out the latest features which are not released yet, or maintain your own fork with patches that cannot be merged to the core.
Assuming you have the Android SDK installed, run android to open the Android SDK Manager.
Make sure you have the following installed:
build.gradle)build.gradle)Android Support Repository) >= 17 (for Android Support Library)Step 1: Set environment variables through your local shell.
Note: Files may vary based on shell flavor. See below for examples from common shells.
.bash_profile or .bashrc.zprofile or .zshrc.profile or $ENVExample:
Step 2: Create a local.properties file in the android directory of your react-native app with the following contents:
Example:
You can find further instructions on the official page.
First, you need to install react-native from your fork. For example, to install the master branch from the official repo, run the following:
Alternatively, you can clone the repo to your node_modules directory and run npm install inside the cloned repo.
Add gradle-download-task as dependency in android/build.gradle:
If you made changes to React Native and submit a pull request, all tests will run on your pull request automatically. To run the tests locally, see Testing.
Gradle build fails in ndk-build. See the section about local.properties file above.
You can edit the content above on GitHub and send us a pull request!
We try our best to deliver buttery-smooth UI performance by default, but sometimes that just isn't possible. Remember, Android supports 10k+ different phones and is generalized to support software rendering: the framework architecture and need to generalize across many hardware targets unfortunately means you get less for free relative to iOS. But sometimes, there are things you can improve (and many times it's not native code's fault at all!).
The first step for debugging this jank is to answer the fundamental question of where your time is being spent during each 16ms frame. For that, we'll be using a standard Android profiling tool called systrace. But first...
Make sure that JS dev mode is OFF!
You should see
__DEV__ === false, development-level warning are OFF, performance optimizations are ONin your application logs (which you can view usingadb logcat)
Systrace is a standard Android marker-based profiling tool (and is installed when you install the Android platform-tools package). Profiled code blocks are surrounded by markers start/end markers which are then visualized in a colorful chart format. Both the Android SDK and React Native framework provide standard markers that you can visualize.
NOTE:
Systrace support was added in react-native
v0.15. You will need to build with that version to collect a trace.
First, connect a device that exhibits the stuttering you want to investigate to your computer via USB and get it to the point right before the navigation/animation you want to profile. Run systrace as follows
A quick breakdown of this command:
time is the length of time the trace will be collected in secondssched, gfx, and view are the android SDK tags (collections of markers) we care about: sched gives you information about what's running on each core of your phone, gfx gives you graphics info such as frame boundaries, and view gives you information about measure, layout, and draw passes-a <your_package_name> enables app-specific markers, specifically the ones built into the React Native framework. your_package_name can be found in the AndroidManifest.xml of your app and looks like com.example.appOnce the trace starts collecting, perform the animation or interaction you care about. At the end of the trace, systrace will give you a link to the trace which you can open in your browser.
After opening the trace in your browser (preferably Chrome), you should see something like this:

If your trace .html file isn't opening correctly, check your browser console for the following:

Since Object.observe was deprecated in recent browsers, you may have to open the file from the Google Chrome Tracing tool. You can do so by:
HINT: Use the WASD keys to strafe and zoom
The first thing you should do is highlight the 16ms frame boundaries if you haven't already done that. Check this checkbox at the top right of the screen:

You should see zebra stripes as in the screenshot above. If you don't, try profiling on a different device: Samsung has been known to have issues displaying vsyncs while the Nexus series is generally pretty reliable.
Scroll until you see (part of) the name of your package. In this case, I was profiling com.facebook.adsmanager, which shows up as book.adsmanager because of silly thread name limits in the kernel.
On the left side, you'll see a set of threads which correspond to the timeline rows on the right. There are three/four threads we care about for our purposes: the UI thread (which has your package name or the name UI Thread), mqt_js and mqt_native_modules. If you're running on Android 5+, we also care about the Render Thread.
This is where standard android measure/layout/draw happens. The thread name on the right will be your package name (in my case book.adsmanager) or UI Thread. The events that you see on this thread should look something like this and have to do with Choreographer, traversals, and DispatchUI:

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

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

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

A smooth animation should look something like the following:

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

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

In this case, the UI and render threads are the ones that have work crossing frame boundaries. The UI that we're trying to render on each frame is requiring too much work to be done. In this case, the problem lies in the native views being rendered.
At this point, you'll have some very helpful information to inform your next steps.
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.
TODO: Add more tools for profiling JS
If you identified a native UI problem, there are usually two scenarios:
In the first scenario, you'll see a trace that has the UI thread and/or Render Thread looking like this:

Notice the long amount of time spent in DrawFrame that crosses frame boundaries. This is time spent waiting for the GPU to drain its command buffer from the previous frame.
To mitigate this, you should:
renderToHardwareTextureAndroid for complex, static content that is being animated/transformed (e.g. the Navigator slide/alpha animations)needsOffscreenAlphaCompositing, which is disabled by default, as it greatly increases the per-frame load on the GPU in most cases.If these don't help and you want to dig deeper into what the GPU is actually doing, you can check out Tracer for OpenGL ES.
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.
If you are confused or stuck, please post ask on Stack Overflow with the react-native tag. If you are unable to get a response there, or find an issue with a core component, please File a Github issue.
You can edit the content above on GitHub and send us a pull request!
We try our best to deliver buttery-smooth UI performance by default, but sometimes that just isn't possible. Remember, Android supports 10k+ different phones and is generalized to support software rendering: the framework architecture and need to generalize across many hardware targets unfortunately means you get less for free relative to iOS. But sometimes, there are things you can improve (and many times it's not native code's fault at all!).
The first step for debugging this jank is to answer the fundamental question of where your time is being spent during each 16ms frame. For that, we'll be using a standard Android profiling tool called systrace. But first...
Make sure that JS dev mode is OFF!
You should see
__DEV__ === false, development-level warning are OFF, performance optimizations are ONin your application logs (which you can view usingadb logcat)
Systrace is a standard Android marker-based profiling tool (and is installed when you install the Android platform-tools package). Profiled code blocks are surrounded by markers start/end markers which are then visualized in a colorful chart format. Both the Android SDK and React Native framework provide standard markers that you can visualize.
NOTE:
Systrace support was added in react-native
v0.15. You will need to build with that version to collect a trace.
First, connect a device that exhibits the stuttering you want to investigate to your computer via USB and get it to the point right before the navigation/animation you want to profile. Run systrace as follows
A quick breakdown of this command:
time is the length of time the trace will be collected in secondssched, gfx, and view are the android SDK tags (collections of markers) we care about: sched gives you information about what's running on each core of your phone, gfx gives you graphics info such as frame boundaries, and view gives you information about measure, layout, and draw passes-a <your_package_name> enables app-specific markers, specifically the ones built into the React Native framework. your_package_name can be found in the AndroidManifest.xml of your app and looks like com.example.appOnce the trace starts collecting, perform the animation or interaction you care about. At the end of the trace, systrace will give you a link to the trace which you can open in your browser.
After opening the trace in your browser (preferably Chrome), you should see something like this:

If your trace .html file isn't opening correctly, check your browser console for the following:

Since Object.observe was deprecated in recent browsers, you may have to open the file from the Google Chrome Tracing tool. You can do so by:
HINT: Use the WASD keys to strafe and zoom
The first thing you should do is highlight the 16ms frame boundaries if you haven't already done that. Check this checkbox at the top right of the screen:

You should see zebra stripes as in the screenshot above. If you don't, try profiling on a different device: Samsung has been known to have issues displaying vsyncs while the Nexus series is generally pretty reliable.
Scroll until you see (part of) the name of your package. In this case, I was profiling com.facebook.adsmanager, which shows up as book.adsmanager because of silly thread name limits in the kernel.
On the left side, you'll see a set of threads which correspond to the timeline rows on the right. There are three/four threads we care about for our purposes: the UI thread (which has your package name or the name UI Thread), mqt_js and mqt_native_modules. If you're running on Android 5+, we also care about the Render Thread.
This is where standard android measure/layout/draw happens. The thread name on the right will be your package name (in my case book.adsmanager) or UI Thread. The events that you see on this thread should look something like this and have to do with Choreographer, traversals, and DispatchUI:

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

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

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

A smooth animation should look something like the following:

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

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

In this case, the UI and render threads are the ones that have work crossing frame boundaries. The UI that we're trying to render on each frame is requiring too much work to be done. In this case, the problem lies in the native views being rendered.
At this point, you'll have some very helpful information to inform your next steps.
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.
TODO: Add more tools for profiling JS
If you identified a native UI problem, there are usually two scenarios:
In the first scenario, you'll see a trace that has the UI thread and/or Render Thread looking like this:

Notice the long amount of time spent in DrawFrame that crosses frame boundaries. This is time spent waiting for the GPU to drain its command buffer from the previous frame.
To mitigate this, you should:
renderToHardwareTextureAndroid for complex, static content that is being animated/transformed (e.g. the Navigator slide/alpha animations)needsOffscreenAlphaCompositing, which is disabled by default, as it greatly increases the per-frame load on the GPU in most cases.If these don't help and you want to dig deeper into what the GPU is actually doing, you can check out Tracer for OpenGL ES.
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.
If you are confused or stuck, please post ask on Stack Overflow with the react-native tag. If you are unable to get a response there, or find an issue with a core component, please File a Github issue.
You can edit the content above on GitHub and send us a pull request!
Animations are an important part of modern UX, and the Animated
+
Animations are an important part of modern UX, and the Animated
library is designed to make them fluid, powerful, and easy to build and
maintain.
The simplest workflow is to create an Animated.Value, hook it up to one or
more style attributes of an animated component, and then drive updates either
@@ -351,7 +351,7 @@ exports.examples : 10,
alignItems: 'center',
},
-});
Fluid, meaningful animations are essential to the mobile user experience. Like +
Fluid, meaningful animations are essential to the mobile user experience. Like
everything in React Native, Animation APIs for React Native are currently under
development, but have started to coalesce around two complementary systems:
LayoutAnimation for animated global layout transactions, and Animated for
@@ -378,7 +378,7 @@ make them customizable, React Native exposes a
pop: CustomLeftToRightGesture,
}
});
For further information about customizing scene transitions, read the -source.
You can edit the content above on GitHub and send us a pull request!
AppRegistry is the JS entry point to running all React Native apps. App
+
AppRegistry is the JS entry point to running all React Native apps. App
root components should register themselves with
AppRegistry.registerComponent, then the native system can load the bundle
for the app and then actually run the app when it's ready by invoking
@@ -12,7 +12,7 @@ sure the JS execution environment is setup before other modules are
the only argument; when the promise is resolved or rejected the native side is
notified of this event and it may decide to destroy the JS context.
Only called from native code. Starts a headless task.
@param taskId the native id for this task instance to keep track of its execution @param taskKey the key for the task to start -@param data the data to pass to the task
You can edit the content above on GitHub and send us a pull request!
AppState can tell you if the app is in the foreground or background,
+
AppState can tell you if the app is in the foreground or background,
and notify you when the state changes.
AppState is frequently used to determine the intent and proper behavior when handling push notifications.
active - The app is running in the foregroundbackground - The app is running in the background. The user is either
in another app or on the home screeninactive - This is a state that occurs when transitioning between
@@ -117,7 +117,7 @@ exports.examples : 'In the IOS simulator, hit Shift+Command+M to simulate a memory warning.',
render(): React.Element<any> { return <AppStateSubscription showMemoryWarnings={true} />; }
},
-];AsyncStorage is a simple, unencrypted, asynchronous, persistent, key-value storage
+
AsyncStorage is a simple, unencrypted, asynchronous, persistent, key-value storage
system that is global to the app. It should be used instead of LocalStorage.
It is recommended that you use an abstraction on top of AsyncStorage
instead of AsyncStorage directly for anything more than light usage since
it operates globally.
On iOS, AsyncStorage is backed by native code that stores small values in a
@@ -217,7 +217,7 @@ exports.examples : 'Basics - getItem, setItem, removeItem',
render(): React.Element<any> { return <BasicStorageExample />; }
},
-];
Detect hardware back button presses, and programmatically invoke the default back button +
Detect hardware back button presses, and programmatically invoke the default back button functionality to exit the app if there are no listeners or if none of the listeners return true. The event subscriptions are called in reverse order (i.e. last registered subscription first), and if one subscription returns true then subscriptions registered earlier will not be called.
Example:
You can edit the content above on GitHub and send us a pull request!
A basic button component that should render nicely on any platform. Supports +
A basic button component that should render nicely on any platform. Supports a minimal level of customization.

If this button doesn't look right for your app, you can build your own @@ -97,7 +97,7 @@ exports.examples ); }, }, -];
CameraRoll provides access to the local camera roll / gallery.
+
CameraRoll provides access to the local camera roll / gallery.
Before using this you must link the RCTCameraRoll library.
You can refer to Linking for help.
Saves the photo or video to the camera roll / gallery.
On Android, the tag must be a local image or video URI, such as "file:///sdcard/img.png".
On iOS, the tag can be any image URI (including local, remote asset-library and base64 data URIs) or a local video file URI (remote or data URIs are not supported for saving video at this time).
If the tag has a file extension of .mov or .mp4, it will be inferred as a video. Otherwise @@ -129,7 +129,7 @@ exports.examples : 'Photos', render(): React.Element<any> { return <CameraRollExample />; } } -];
Clipboard gives you an interface for setting and getting content from Clipboard on both iOS and Android
Get content of string type, this method returns a Promise, so you can use following code to get clipboard content
Clipboard gives you an interface for setting and getting content from Clipboard on both iOS and Android
Get content of string type, this method returns a Promise, so you can use following code to get clipboard content
Set content of string type. You can use following code to set clipboard content
The following formats are supported:
'#f0f' (#rgb)'#f0fc' (#rgba)'#ff00ff' (#rrggbb)'#ff00ff00' (#rrggbbaa)'rgb(255, 255, 255)''rgba(255, 255, 255, 1.0)''hsl(360, 100%, 100%)''hsla(360, 100%, 100%, 1.0)''transparent''red'0xff00ff00 (0xrrggbbaa)For the named colors, React Native follows the CSS3 specification:
You can edit the content above on GitHub and send us a pull request!
The following formats are supported:
'#f0f' (#rgb)'#f0fc' (#rgba)'#ff00ff' (#rrggbb)'#ff00ff00' (#rrggbbaa)'rgb(255, 255, 255)''rgba(255, 255, 255, 1.0)''hsl(360, 100%, 100%)''hsla(360, 100%, 100%, 1.0)''transparent''red'0xff00ff00 (0xrrggbbaa)For the named colors, React Native follows the CSS3 specification:
You can edit the content above on GitHub and send us a pull request!
In Integrating with Existing Apps guide and Native UI Components guide we learn how to embed React Native in a native component and vice versa. When we mix native and React Native components, we'll eventually find a need to communicate between these two worlds. Some ways to achieve that have been already mentioned in other guides. This article summarizes available techniques.
React Native is inspired by React, so the basic idea of the information flow is similar. The flow in React is one-directional. We maintain a hierarchy of components, in which each component depends only on its parent and own internal state. We do this with properties: data is passed from a parent to its children in a top-down manner. If we have an ancestor component that rely on the state of its descendant, the recommended solution would be to pass down a callback that would be used by the descendant to update the ancestor.
The same concept applies to React Native. As long as we are building our application purely within the framework, we can drive our app with properties and callbacks. But, when we mix React Native and native components, we need some special, cross-language mechanisms that would allow us to pass information between them.
Properties are the simplest way of cross-component communication. So we need a way to pass properties both from native to React Native, and from React Native to native.
In order to embed a React Native view in a native component, we use RCTRootView. RCTRootView is a UIView that holds a React Native app. It also provides an interface between native side and the hosted app.
RCTRootView has an initializer that allows you to pass arbitrary properties down to the React Native app. The initialProperties parameter has to be an instance of NSDictionary. The dictionary is internally converted into a JSON object that the top-level JS component can reference.
In Integrating with Existing Apps guide and Native UI Components guide we learn how to embed React Native in a native component and vice versa. When we mix native and React Native components, we'll eventually find a need to communicate between these two worlds. Some ways to achieve that have been already mentioned in other guides. This article summarizes available techniques.
React Native is inspired by React, so the basic idea of the information flow is similar. The flow in React is one-directional. We maintain a hierarchy of components, in which each component depends only on its parent and own internal state. We do this with properties: data is passed from a parent to its children in a top-down manner. If we have an ancestor component that rely on the state of its descendant, the recommended solution would be to pass down a callback that would be used by the descendant to update the ancestor.
The same concept applies to React Native. As long as we are building our application purely within the framework, we can drive our app with properties and callbacks. But, when we mix React Native and native components, we need some special, cross-language mechanisms that would allow us to pass information between them.
Properties are the simplest way of cross-component communication. So we need a way to pass properties both from native to React Native, and from React Native to native.
In order to embed a React Native view in a native component, we use RCTRootView. RCTRootView is a UIView that holds a React Native app. It also provides an interface between native side and the hosted app.
RCTRootView has an initializer that allows you to pass arbitrary properties down to the React Native app. The initialProperties parameter has to be an instance of NSDictionary. The dictionary is internally converted into a JSON object that the top-level JS component can reference.
In the example we have a FlexibleSizeExampleView view that holds a root view. We create the root view, initialize it and set the delegate. The delegate will handle size updates. Then, we set the root view's size flexibility to RCTRootViewSizeFlexibilityHeight, which means that rootViewDidChangeIntrinsicSize: method will be called every time the React Native content changes its height. Finally, we set the root view's width and position. Note that we set there height as well, but it has no effect as we made the height RN-dependent.
You can checkout full source code of the example here.
It's fine to change root view's size flexibility mode dynamically. Changing flexibility mode of a root view will schedule a layout recalculation and the delegate rootViewDidChangeIntrinsicSize: method will be called once the content size is known.
Note: React Native layout calculation is performed on a special thread, while native UI view updates are done on the main thread. This may cause temporary UI inconsistencies between native and React Native. This is a known problem and our team is working on synchronizing UI updates coming from different sources.
Note: React Native does not perform any layout calculations until the root view becomes a subview of some other views. If you want to hide React Native view until its dimensions are known, add the root view as a subview and make it initially hidden (use
UIView'shiddenproperty). Then change its visibility in the delegate method.
You can edit the content above on GitHub and send us a pull request!
Opens the standard Android date picker dialog.
Opens the standard Android date picker dialog.
Opens the standard Android date picker dialog.
The available keys for the options object are:
date (Date object or timestamp in milliseconds) - date to show by default
minDate (Date or timestamp in milliseconds) - minimum date that can be selected
- * maxDate (Date object or timestamp in milliseconds) - minimum date that can be selected
Returns a Promise which will be invoked an object containing action, year, month (0-11),
+ maxDate (Date object or timestamp in milliseconds) - minimum date that can be selected
+ mode (enum('calendar', 'spinner', 'default')) - To set the date-picker mode to calendar/spinner/default
+ - 'calendar': Show a date picker in calendar mode.
+ - 'spinner': Show a date picker in spinner mode.
+ - 'default': Show a default native date picker(spinner/calendar) based on android versions.
Returns a Promise which will be invoked an object containing action, year, month (0-11),
day if the user picked a date. If the user dismissed the dialog, the Promise will
still be resolved with action being DatePickerAndroid.dismissedAction and all the other keys
being undefined. Always check whether the action before reading the values.
Note the native date picker dialog has some UI glitches on Android 4 and lower
@@ -38,6 +42,9 @@ class DatePickerAndroidExample extends
Use DatePickerIOS to render a date/time picker (selector) on iOS. This is
+
Use DatePickerIOS to render a date/time picker (selector) on iOS. This is
a controlled component, so you must hook in to the onDateChange callback
and update the date prop in order for the component to update, otherwise
the user's change will be reverted immediately to reflect props.date as the
@@ -155,7 +155,7 @@ exports.examples : '500',
fontSize: 14,
},
-});
You can access the developer menu by shaking your device or by selecting "Shake Gesture" inside the Hardware menu in the iOS Simulator. You can also use the Command⌘ + D keyboard shortcut when your app is running in the iPhone Simulator, or Command⌘ + M when running in an Android emulator.

The Developer Menu is disabled in release (production) builds.
Instead of recompiling your app every time you make a change, you can reload your app's JavaScript code instantly. To do so, select "Reload" from the Developer Menu. You can also press Command⌘ + R in the iOS Simulator, or press R twice on Android emulators.
If the
Command⌘+Rkeyboard shortcut does not seem to reload the iOS Simulator, go to the Hardware menu, select Keyboard, and make sure that "Connect Hardware Keyboard" is checked.
You can speed up your development times by having your app reload automatically any time your code changes. Automatic reloading can be enabled by selecting "Enable Live Reload" from the Developer Menu.
You may even go a step further and keep your app running as new versions of your files are injected into the JavaScript bundle automatically by enabling Hot Reloading from the Developer Menu. This will allow you to persist the app's state through reloads.
There are some instances where hot reloading cannot be implemented perfectly. If you run into any issues, use a full reload to reset your app.
You will need to rebuild your app for changes to take effect in certain situations:
Images.xcassets on iOS or the res/drawable folder on Android.Errors and warnings are displayed inside your app in development builds.
In-app errors are displayed in a full screen alert with a red background inside your app. This screen is known as a RedBox. You can use console.error() to manually trigger one.
Warnings will be displayed on screen with a yellow background. These alerts are known as YellowBoxes. Click on the alerts to show more information or to dismiss them.
As with a RedBox, you can use console.warn() to trigger a YellowBox.
YellowBoxes can be disabled during development by using console.disableYellowBox = true;. Specific warnings can be ignored programmatically by setting an array of prefixes that should be ignored: console.ignoredYellowBox = ['Warning: ...'];
RedBoxes and YellowBoxes are automatically disabled in release (production) builds.
You can display the console logs for an iOS or Android app by using the following commands in a terminal while the app is running:
You can access the developer menu by shaking your device or by selecting "Shake Gesture" inside the Hardware menu in the iOS Simulator. You can also use the Command⌘ + D keyboard shortcut when your app is running in the iPhone Simulator, or Command⌘ + M when running in an Android emulator.

The Developer Menu is disabled in release (production) builds.
Instead of recompiling your app every time you make a change, you can reload your app's JavaScript code instantly. To do so, select "Reload" from the Developer Menu. You can also press Command⌘ + R in the iOS Simulator, or press R twice on Android emulators.
If the
Command⌘+Rkeyboard shortcut does not seem to reload the iOS Simulator, go to the Hardware menu, select Keyboard, and make sure that "Connect Hardware Keyboard" is checked.
You can speed up your development times by having your app reload automatically any time your code changes. Automatic reloading can be enabled by selecting "Enable Live Reload" from the Developer Menu.
You may even go a step further and keep your app running as new versions of your files are injected into the JavaScript bundle automatically by enabling Hot Reloading from the Developer Menu. This will allow you to persist the app's state through reloads.
There are some instances where hot reloading cannot be implemented perfectly. If you run into any issues, use a full reload to reset your app.
You will need to rebuild your app for changes to take effect in certain situations:
Images.xcassets on iOS or the res/drawable folder on Android.Errors and warnings are displayed inside your app in development builds.
In-app errors are displayed in a full screen alert with a red background inside your app. This screen is known as a RedBox. You can use console.error() to manually trigger one.
Warnings will be displayed on screen with a yellow background. These alerts are known as YellowBoxes. Click on the alerts to show more information or to dismiss them.
As with a RedBox, you can use console.warn() to trigger a YellowBox.
YellowBoxes can be disabled during development by using console.disableYellowBox = true;. Specific warnings can be ignored programmatically by setting an array of prefixes that should be ignored: console.ignoredYellowBox = ['Warning: ...'];
RedBoxes and YellowBoxes are automatically disabled in release (production) builds.
You can display the console logs for an iOS or Android app by using the following commands in a terminal while the app is running:
You may also access these through Debug → Open System Log... in the iOS Simulator or by running adb logcat *:S ReactNative:V ReactNativeJS:V in a terminal while an Android app is running on a device or emulator.
To debug the JavaScript code in Chrome, select "Debug JS Remotely" from the Developer Menu. This will open a new tab at http://localhost:8081/debugger-ui.
Select Tools → Developer Tools from the Chrome Menu to open the Developer Tools. You may also access the DevTools using keyboard shortcuts (Command⌘ + Option⌥ + I on Mac, Ctrl + Shift + I on Windows). You may also want to enable Pause On Caught Exceptions for a better debugging experience.
It is currently not possible to use the "React" tab in the Chrome Developer Tools to inspect app widgets. You can use Nuclide's "React Native Inspector" as a workaround.
On iOS devices, open the file RCTWebSocketExecutor.m and change "localhost" to the IP address of your computer, then select "Debug JS Remotely" from the Developer Menu.
On Android 5.0+ devices connected via USB, you can use the adb command line tool to setup port forwarding from the device to your computer:
adb reverse tcp:8081 tcp:8081
Alternatively, select "Dev Settings" from the Developer Menu, then update the "Debug server host for device" setting to match the IP address of your computer.
If you run into any issues, it may be possible that one of your Chrome extensions is interacting in unexpected ways with the debugger. Try disabling all of your extensions and re-enabling them one-by-one until you find the problematic extension.
To use a custom JavaScript debugger in place of Chrome Developer Tools, set the REACT_DEBUGGER environment variable to a command that will start your custom debugger. You can then select "Debug JS Remotely" from the Developer Menu to start debugging.
The debugger will receive a list of all project roots, separated by a space. For example, if you set REACT_DEBUGGER="node /path/to/launchDebugger.js --port 2345 --type ReactNative", then the command node /path/to/launchDebugger.js --port 2345 --type ReactNative /path/to/reactNative/app will be used to start your debugger.
Custom debugger commands executed this way should be short-lived processes, and they shouldn't produce more than 200 kilobytes of output.
In android/app/build.gradle, add these lines in the dependencies section:
In android/app/src/main/java/com/{yourAppName}/MainApplication.java, add the following imports:
Run react-native run-android
In a new chrome tab, open : chrome://inspect, click on 'Inspect device' (the one followed by "Powered by Stetho")
When working with native code (e.g. when writing native modules) you can launch the app from Android Studio or Xcode and take advantage of the debugging features (setup breakpoints, etc.) as you would in case of building a standard native app.
You can enable a performance overlay to help you debug performance problems by selecting "Perf Monitor" in the Developer Menu.
You can edit the content above on GitHub and send us a pull request!
This should only be called from native code by sending the +
This should only be called from native code by sending the didUpdateDimensions event.
@param {object} dims Simple string-keyed object of dimensions to set
Initial dimensions are set before runApplication is called so they should
be available before any other require's are run, but may be updated later.
Note: Although dimensions are available immediately, they may change (e.g
due to device rotation) so any rendering logic or styles that depend on
these constants should try to call this function on every render, rather
than caching the value (for example, using inline styles rather than
setting a value in a StyleSheet).
Example: var {height, width} = Dimensions.get('window');
@param {string} dim Name of dimension as defined when calling set.
-@returns {Object?} Value for the dimension.
You can edit the content above on GitHub and send us a pull request!
It is sometimes necessary to make changes directly to a component +
It is sometimes necessary to make changes directly to a component
without using state/props to trigger a re-render of the entire subtree.
When using React in the browser for example, you sometimes need to
directly modify a DOM node, and the same is true for views in mobile
@@ -136,7 +136,7 @@ the jerky animation each 250ms when setState triggers a re-render.<
shouldComponentUpdate
you can avoid the unnecessary overhead involved in reconciling unchanged
component subtrees, to the point where it may be performant enough to
-use setState instead of setNativeProps.
You can edit the content above on GitHub and send us a pull request!
React component that wraps the platform DrawerLayout (Android only). The
+
React component that wraps the platform DrawerLayout (Android only). The
Drawer (typically used for navigation) is rendered with renderNavigationView
and direct children are the main view (where your content goes). The navigation
view is initially not visible on the screen, but can be pulled in from the
@@ -37,7 +37,7 @@ from the edge of the window.
The navigation view that will be rendered to the side of the screen and can be pulled in.
You can edit the content above on GitHub and send us a pull request!
This class implements common easing functions. The math is pretty obscure, +
This class implements common easing functions. The math is pretty obscure, but this cool website has nice visual illustrations of what they represent: http://xaedes.de/dev/transitions/
A simple elastic interaction, similar to a spring. Default bounciness is 1, which overshoots a little bit once. 0 bounciness doesn't overshoot at all, and bounciness of N > 1 will overshoot about N times.
Wolfram Plots:
http://tiny.cc/elastic_b_1 (default bounciness = 1) - http://tiny.cc/elastic_b_3 (bounciness = 3)
Runs an easing function backwards.
Makes any easing function symmetrical.
You can edit the content above on GitHub and send us a pull request!
A component can specify the layout of its children using the flexbox algorithm. Flexbox is designed to provide a consistent layout on different screen sizes.
You will normally use a combination of flexDirection, alignItems, and justifyContent to achieve the right layout.
Flexbox works the same way in React Native as it does in CSS on the web, with a few exceptions. The defaults are different, with
flexDirectiondefaulting tocolumninstead ofrow, andalignItemsdefaulting tostretchinstead offlex-start, and theflexparameter only supports a single number.
Adding flexDirection to a component's style determines the primary axis of its layout. Should the children be organized horizontally (row) or vertically (column)? The default is column.
A component can specify the layout of its children using the flexbox algorithm. Flexbox is designed to provide a consistent layout on different screen sizes.
You will normally use a combination of flexDirection, alignItems, and justifyContent to achieve the right layout.
Flexbox works the same way in React Native as it does in CSS on the web, with a few exceptions. The defaults are different, with
flexDirectiondefaulting tocolumninstead ofrow, and theflexparameter only supporting a single number.
Adding flexDirection to a component's style determines the primary axis of its layout. Should the children be organized horizontally (row) or vertically (column)? The default is column.
We've covered the basics, but there are many other styles you may need for layouts. The full list of props that control layout is documented here.
We're getting close to being able to build a real application. One thing we are still missing is a way to take user input, so let's move on to learn how to handle text input with the TextInput component.
You can edit the content above on GitHub and send us a pull request!
The Geolocation API extends the web spec: +
The Geolocation API extends the web spec: https://developer.mozilla.org/en-US/docs/Web/API/Geolocation
As a browser polyfill, this API is available through the navigator.geolocation
global - you do not need to import it.
You need to include the NSLocationWhenInUseUsageDescription key
in Info.plist to enable geolocation when using the app. Geolocation is
@@ -82,7 +82,7 @@ class GeolocationExample extends : {
fontWeight: '500',
},
-});
Gesture recognition on mobile devices is much more complicated than web. A touch can go through several phases as the app determines what the user's intention is. For example, the app needs to determine if the touch is scrolling, sliding on a widget, or tapping. This can even change during the duration of a touch. There can also be multiple simultaneous touches.
The touch responder system is needed to allow components to negotiate these touch interactions without any additional knowledge about their parent or child components. This system is implemented in ResponderEventPlugin.js, which contains further details and documentation.
Users can feel huge differences in the usability of web apps vs. native, and this is one of the big causes. Every action should have the following attributes:
These features make users more comfortable while using an app, because it allows people to experiment and interact without fear of making mistakes.
The responder system can be complicated to use. So we have provided an abstract Touchable implementation for things that should be "tappable". This uses the responder system and allows you to easily configure tap interactions declaratively. Use TouchableHighlight anywhere where you would use a button or link on web.
A view can become the touch responder by implementing the correct negotiation methods. There are two methods to ask the view if it wants to become responder:
View.props.onStartShouldSetResponder: (evt) => true, - Does this view want to become responder on the start of a touch?View.props.onMoveShouldSetResponder: (evt) => true, - Called for every touch move on the View when it is not the responder: does this view want to "claim" touch responsiveness?If the View returns true and attempts to become the responder, one of the following will happen:
View.props.onResponderGrant: (evt) => {} - The View is now responding for touch events. This is the time to highlight and show the user what is happeningView.props.onResponderReject: (evt) => {} - Something else is the responder right now and will not release itIf the view is responding, the following handlers can be called:
View.props.onResponderMove: (evt) => {} - The user is moving their fingerView.props.onResponderRelease: (evt) => {} - Fired at the end of the touch, ie "touchUp"View.props.onResponderTerminationRequest: (evt) => true - Something else wants to become responder. Should this view release the responder? Returning true allows releaseView.props.onResponderTerminate: (evt) => {} - The responder has been taken from the View. Might be taken by other views after a call to onResponderTerminationRequest, or might be taken by the OS without asking (happens with control center/ notification center on iOS)evt is a synthetic touch event with the following form:
nativeEventchangedTouches - Array of all touch events that have changed since the last eventidentifier - The ID of the touchlocationX - The X position of the touch, relative to the elementlocationY - The Y position of the touch, relative to the elementpageX - The X position of the touch, relative to the root elementpageY - The Y position of the touch, relative to the root elementtarget - The node id of the element receiving the touch eventtimeStamp - A time identifier for the touch, useful for velocity calculationtouches - Array of all current touches on the screenonStartShouldSetResponder and onMoveShouldSetResponder are called with a bubbling pattern, where the deepest node is called first. That means that the deepest component will become responder when multiple Views return true for *ShouldSetResponder handlers. This is desirable in most cases, because it makes sure all controls and buttons are usable.
However, sometimes a parent will want to make sure that it becomes responder. This can be handled by using the capture phase. Before the responder system bubbles up from the deepest component, it will do a capture phase, firing on*ShouldSetResponderCapture. So if a parent View wants to prevent the child from becoming responder on a touch start, it should have a onStartShouldSetResponderCapture handler which returns true.
View.props.onStartShouldSetResponderCapture: (evt) => true,View.props.onMoveShouldSetResponderCapture: (evt) => true,For higher-level gesture interpretation, check out PanResponder.
You can edit the content above on GitHub and send us a pull request!
The gesture responder system manages the lifecycle of gestures in your app. A touch can go through several phases as the app determines what the user's intention is. For example, the app needs to determine if the touch is scrolling, sliding on a widget, or tapping. This can even change during the duration of a touch. There can also be multiple simultaneous touches.
The touch responder system is needed to allow components to negotiate these touch interactions without any additional knowledge about their parent or child components. This system is implemented in ResponderEventPlugin.js, which contains further details and documentation.
To make your app feel great, every action should have the following attributes:
These features make users more comfortable while using an app, because it allows people to experiment and interact without fear of making mistakes.
The responder system can be complicated to use. So we have provided an abstract Touchable implementation for things that should be "tappable". This uses the responder system and allows you to easily configure tap interactions declaratively. Use TouchableHighlight anywhere where you would use a button or link on web.
A view can become the touch responder by implementing the correct negotiation methods. There are two methods to ask the view if it wants to become responder:
View.props.onStartShouldSetResponder: (evt) => true, - Does this view want to become responder on the start of a touch?View.props.onMoveShouldSetResponder: (evt) => true, - Called for every touch move on the View when it is not the responder: does this view want to "claim" touch responsiveness?If the View returns true and attempts to become the responder, one of the following will happen:
View.props.onResponderGrant: (evt) => {} - The View is now responding for touch events. This is the time to highlight and show the user what is happeningView.props.onResponderReject: (evt) => {} - Something else is the responder right now and will not release itIf the view is responding, the following handlers can be called:
View.props.onResponderMove: (evt) => {} - The user is moving their fingerView.props.onResponderRelease: (evt) => {} - Fired at the end of the touch, ie "touchUp"View.props.onResponderTerminationRequest: (evt) => true - Something else wants to become responder. Should this view release the responder? Returning true allows releaseView.props.onResponderTerminate: (evt) => {} - The responder has been taken from the View. Might be taken by other views after a call to onResponderTerminationRequest, or might be taken by the OS without asking (happens with control center/ notification center on iOS)evt is a synthetic touch event with the following form:
nativeEventchangedTouches - Array of all touch events that have changed since the last eventidentifier - The ID of the touchlocationX - The X position of the touch, relative to the elementlocationY - The Y position of the touch, relative to the elementpageX - The X position of the touch, relative to the root elementpageY - The Y position of the touch, relative to the root elementtarget - The node id of the element receiving the touch eventtimeStamp - A time identifier for the touch, useful for velocity calculationtouches - Array of all current touches on the screenonStartShouldSetResponder and onMoveShouldSetResponder are called with a bubbling pattern, where the deepest node is called first. That means that the deepest component will become responder when multiple Views return true for *ShouldSetResponder handlers. This is desirable in most cases, because it makes sure all controls and buttons are usable.
However, sometimes a parent will want to make sure that it becomes responder. This can be handled by using the capture phase. Before the responder system bubbles up from the deepest component, it will do a capture phase, firing on*ShouldSetResponderCapture. So if a parent View wants to prevent the child from becoming responder on a touch start, it should have a onStartShouldSetResponderCapture handler which returns true.
View.props.onStartShouldSetResponderCapture: (evt) => true,View.props.onMoveShouldSetResponderCapture: (evt) => true,For higher-level gesture interpretation, check out PanResponder.
You can edit the content above on GitHub and send us a pull request!
Welcome to React Native! This page will help you install React Native on +
Welcome to React Native! This page will help you install React Native on your system, so that you can build apps with it right away. If you already have React Native installed, you can skip ahead to the Tutorial.
The instructions are a bit different depending on your development operating system, and whether you want to start developing for iOS or Android. If you @@ -63,17 +63,16 @@ changes in the filesystem. It is highly recommended you install it for better pe
We recommend installing Node.js and Python2 via Chocolatey, a popular package manager for Windows. Open a Command Prompt as Administrator, then run:
You can find additional installation options on Node.js's Downloads page.
Node.js comes with npm, which lets you install the React Native command line interface.
Node.js comes with npm, which lets you install the React Native command line interface.
Run the following command in a Terminal:
If you get an error like
Cannot find module 'npmlog', try installing npm directly:curl -0 -L http://npmjs.org/install.sh | sudo sh.
Node.js comes with npm, which lets you install the React Native command line interface.
Run the following command in a Terminal:
If you get a permission error, try using sudo:
sudo npm install -g react-native-cli.If you get an error like
Cannot find module 'npmlog', try installing npm directly:curl -0 -L http://npmjs.org/install.sh | sudo sh.
Node.js comes with npm, which lets you install the React Native command line interface.
Run the following command in a Terminal:
If you get an error like
Cannot find module 'npmlog', try installing npm directly:curl -0 -L http://npmjs.org/install.sh | sudo sh.
The easiest way to install Xcode is via the Mac App Store. Installing Xcode will also install the iOS Simulator and all the necessary tools to build your iOS app.
Setting up your development environment can be somewhat tedious if you're new to Android development. If you're already familiar with Android development, there are a few things you may need to configure. In either case, please make sure to carefully follow the next few steps.
Android Studio provides the Android SDK and AVD (emulator) required to run and test your React Native apps.
Android Studio requires the Java Development Kit (JDK), version 1.8 or higher. You can type
javac -versionin a terminal to see what version you have, if any.
Android Studio requires the Java SE Development Kit(JDK), version 8. You can type
javac -versionin a terminal to see what version you have, if any.
The version string
1.8.x_xxxcorresponds to JDK 8.
Choose Custom installation when running Android Studio for the first time. Make sure the boxes next to all of the following are checked:
Android SDKAndroid SDK PlatformPerformance (Intel ® HAXM)Android Virtual DeviceThen, click "Next" to install all of these components.
If you've already installed Android Studio before, you can still install HAXM without performing a custom installation.
Please make sure you export the correct path for
ANDROID_HOMEif you did not install the Android SDK using Android Studio.
Go to Control Panel → System and Security → System → Change settings → -Advanced System Settings → Environment variables → New, then enter the path to your Android SDK.

Restart the Command Prompt to apply the new environment variable.
Please make sure you export the correct path for
ANDROID_HOMEif you did not install the Android SDK using Android Studio.

Restart the Command Prompt to apply the new environment variable.
Please make sure you export the correct path for
ANDROID_HOMEif you did not install the Android SDK using Android Studio.
Follow the Watchman installation guide to compile and install Watchman from source.
Watchman is a tool by Facebook for watching changes in the filesystem. It is highly recommended you install it for better performance, but it's alright to skip this if you find the process to be tedious.
You can edit the content above on GitHub and send us a pull request!
TextInput is a basic component that allows the user to enter text. It has an onChangeText prop that takes
+
TextInput is a basic component that allows the user to enter text. It has an onChangeText prop that takes
a function to be called every time the text changed, and an onSubmitEditing prop that takes a function to be called when the text is submitted.
For example, let's say that as the user types, you're translating their words into a different language. In this new language, every single word is written the same way: 🍕. So the sentence "Hello there Bob" would be translated as "🍕🍕🍕".
In this example, we store text in the state, because it changes over time.
There are a lot more things you might want to do with a text input. For example, you could validate the text inside while the user types. For more detailed examples, see the React docs on controlled components, or the reference docs for TextInput.
Text input is probably the simplest example of a component whose state naturally changes over time. Next, let's look at another type of component like this one that controls layout, and learn about the ScrollView.
You can edit the content above on GitHub and send us a pull request!
Users interact with mobile apps mainly through touch. They can use a combination of gestures, such as tapping on a button, scrolling a list, or zooming on a map.
React Native provides components to handle common gestures, such as taps and swipes, as well as a comprehensive gesture responder system to allow for more advanced gesture recognition.
You can use "Touchable" components when you want to capture a tapping gesture. They take a function through the onPress props which will be called when the touch begins and ends within the bounds of the component.
Example:
Users interact with mobile apps mainly through touch. They can use a combination of gestures, such as tapping on a button, scrolling a list, or zooming on a map.
React Native provides components to handle common gestures, such as taps and swipes, as well as a comprehensive gesture responder system to allow for more advanced gesture recognition.
You can use "Touchable" components when you want to capture a tapping gesture. They take a function through the onPress props which will be called when the touch begins and ends within the bounds of the component.
Example:
Tappable components should provide feedback that show the user what is handling their touch, and what will happen when they lift their finger. The user should also be able to cancel a tap by dragging their finger away.
Which component you use will depend on what kind of feedback you want to provide:
Generally, you can use TouchableHighlight anywhere you would use a button or link on web. The view's background will be darkened when the user presses down on the button.
You may consider using TouchableNativeFeedback on Android to display ink surface reaction ripples that respond to the user's touch.
TouchableOpacity can be used to provide feedback by reducing the opacity of the button, allowing the background to be seen through while the user is pressing down.
If you need to handle a tap gesture but you don't want any feedback to be displayed, use TouchableWithoutFeedback.
In some cases, you may want to detect when a user presses and holds a view for a set amount of time. These long presses can be handled by passing a function to the onLongPress props of any of the touchable components listed above.
A common pattern to many mobile apps is the scrollable list of items. Users interact with these using panning or swiping gestures. The ScrollView component displays a list of items that can be scrolled using these gestures.
ScrollViews can scroll vertically or horizontally, and can be configured to allow paging through views using swiping gestures by using the pagingEnabled props. Swiping horizontally between views can also be implemented on Android using the ViewPagerAndroid component.
A ListView is a special kind of ScrollView that is best suited for displaying long vertical lists of items. It can also display section headers and footers, similar to UITableViews on iOS.
A ScrollView with a single item can be used to allow the user to zoom content. Set up the maximumZoomScale and minimumZoomScale props and your user will be able to use pinch and expand gestures to zoom in and out.
If you want to allow a user to drag a view around the screen, or you want to implement your own custom pan/drag gesture, take a look at the PanResponder API or the gesture responder system docs.
You can edit the content above on GitHub and send us a pull request!
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.
A task is a simple async function that you register on AppRegistry, similar to registering React applications:
Then, in SomeTaskName.js:
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.
A task is a simple async function that you register on AppRegistry, similar to registering React applications:
Then, in SomeTaskName.js:
You can do anything in your task as long as it doesn't touch UI: network requests, timers and so on. Once your task completes (i.e. the promise is resolved), React Native will go into "paused" mode (unless there are other tasks running, or there is a foreground app).
Yes, this does still require some native code, but it's pretty thin. You need to extend HeadlessJsTaskService and override getTaskConfig, e.g.:
Now, whenever you start your service, e.g. as a periodic task or in response to some system event / broadcast, JS will spin up, run your task, then spin down.
BroadcastReceiver, make sure to call HeadlessJsTaskService.acquireWakelockNow() before returning from onReceive().You can edit the content above on GitHub and send us a pull request!
A component's height and width determine its size on the screen.
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.
A component's height and width determine its size on the screen.
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.
After you can control a component's size, the next step is to learn how to lay it out on the screen.
You can edit the content above on GitHub and send us a pull request!
A React component for displaying different types of images, +
A React component for displaying different types of images, including network images, static resources, temporary local images, and images from local disk, such as the camera roll.
This example shows both fetching and displaying an image from local storage as well as on from network.
Crop the image specified by the URI param. If URI points to a remote +
Crop the image specified by the URI param. If URI points to a remote image, it will be downloaded automatically. If the image cannot be loaded/downloaded, the failure callback will be called.
If the cropping process is successful, the resultant cropped image will be stored in the ImageStore, and the URI returned in the success callback will point to the image in the store. Remember to delete the -cropped image from the ImageStore when you are done with it.
You can edit the content above on GitHub and send us a pull request!
React Native provides a unified way of managing images in your iOS and Android apps. To add a static image to your app, place it somewhere in your source code tree and reference it like this:
The image name is resolved the same way JS modules are resolved. In the example above, the packager will look for my-icon.png in the same folder as the component that requires it. Also, if you have my-icon.ios.png and my-icon.android.png, the packager will pick the correct file for the platform.
You can also use the @2x and @3x suffixes to provide images for different screen densities. If you have the following file structure:
React Native provides a unified way of managing images in your iOS and Android apps. To add a static image to your app, place it somewhere in your source code tree and reference it like this:
The image name is resolved the same way JS modules are resolved. In the example above, the packager will look for my-icon.png in the same folder as the component that requires it. Also, if you have my-icon.ios.png and my-icon.android.png, the packager will pick the correct file for the platform.
You can also use the @2x and @3x suffixes to provide images for different screen densities. If you have the following file structure:
Images.xcassets.Please note that the following corner specific, border radius style properties are currently ignored by iOS's image component:
borderTopLeftRadiusborderTopRightRadiusborderBottomLeftRadiusborderBottomRightRadiusImage decoding can take more than a frame-worth of time. This is one of the major sources of frame drops on the web because decoding is done in the main thread. In React Native, image decoding is done in a different thread. In practice, you already need to handle the case when the image is not downloaded yet, so displaying the placeholder for a few more frames while it is decoding does not require any code change.
You can edit the content above on GitHub and send us a pull request!
Check if the ImageStore contains image data for the specified URI. +
Check if the ImageStore contains image data for the specified URI. @platform ios
Delete an image from the ImageStore. Images are stored in memory and must be manually removed when you are finished with them, otherwise they will continue to use up RAM until the app is terminated. It is safe to @@ -16,7 +16,7 @@ will be called.
Note that it is very inefficient to transfer large quantit
data between JS and native code, so you should avoid calling this more
than necessary. To display an image in the ImageStore, you can just pass
the URI to an <Image/> component; there is no need to retrieve the
-base64 data.
You can edit the content above on GitHub and send us a pull request!