We’ve been working on React Native CI. Most importantly, we have migrated from Travis to Circle, leaving React Native with a single, unified CI pipeline.
We’ve organised Hacktoberfest - React Native edition where, together with attendees, we tried to submit many pull requests to open source projects.
We keep working on Haul. Last month, we have submitted two new releases, including Webpack 3 support. We plan to add CRNA and Expo support as well as work on better HMR. Our roadmap is public on the issue tracker. If you would like to suggest improvements or give feedback, let us know!
Focus our attention on rough edges when building large applications with Expo. For example:
First-class support for deploying to multiple environments: staging, production, and arbitrary channels. Channels will support rolling back and setting the active release for a given channel. Let us know if you want to be an early tester, @expo_io.
We are also working on improving our standalone app building infrastructure and adding support for bundling images and other non-code assets in standalone app builds while keeping the ability to update assets over the air.
The meaning of “left” and “right” were swapped in RTL for position, margin, padding, and border styles. Within a few months, we’re going to remove this behaviour and make “left” always mean “left,” and “right” always mean “right”. The breaking changes are hidden under a flag. Use I18nManager.swapLeftAndRightInRTL(false) in your React Native components to opt into them.
Working on Flow typing our internal native modules and using those to generate interfaces in Java and protocols in ObjC that the native implementations must implement. We hope this codegen becomes open source next year, at the earliest.
Improving the development flow on Shoutem. We want to streamline the process from creating an app to first custom screen and make it really easy, thus lowering the barrier for new React Native developers. Prepared a few workshops to test out new features. We also improved Shoutem CLI to support new flows.
Shoutem UI received a few component improvements and bugfixes. We also checked compatibility with latest React Native versions.
Shoutem platform received a few notable updates, new integrations are available as part of the open-source extensions project. We are really excited to see active development on Shoutem extensions from other developers. We actively contact and offer advice and guidance about their extensions.
The next session is scheduled for Wednesday 6, December 2017. Feel free to ping me on Twitter if you have any suggestion on how we should improve the output of the meeting.
The React Native monthly meeting continues! This month's meeting was a bit shorter as most of our teams were busy shipping. Next month, we are at React Native EU conference in Wroclaw, Poland. Make sure to grab a ticket and see you there in person! Meanwhile, let's see what our teams are up to.
React Native is used in multiple places across multiple apps in the Facebook family including a top level tab in the main Facebook apps. Our focus for this post is a highly visible product, Marketplace. It is available in a dozen or so countries and enables users to discover products and services provided by other users.
The React Native monthly meeting continues! On this session, we were joined by Infinite Red, great minds behind Chain React, the React Native Conference. As most of the people here were presenting talks at Chain React, we pushed the meeting to a week later. Talks from the conference have been posted online and I encourage you to check them out. So, let's see what our teams are up to.
At Shoutem, we've been fortunate enough to work with React Native from its very beginnings. We decided we wanted to be part of the amazing community from day one. Soon enough, we realized it's almost impossible to keep up with the pace the community was growing and improving. That's why we decided to organize a monthly meeting where all major React Native contributors can briefly present what their efforts and plans are.
Today we’re announcing Create React Native App: a new tool that makes it significantly easier to get started with a React Native project! It’s heavily inspired by the design of Create React App and is the product of a collaboration between Facebook and Expo (formerly Exponent).
At Facebook, we often need to access deeply nested values in data structures fetched with GraphQL. On the way to accessing these deeply nested values, it is common for one or more intermediate fields to be nullable. These intermediate fields may be null for a variety of reasons, from failed privacy checks to the mere fact that null happens to be the most flexible way to represent non-fatal errors.
Many of you have started playing with some of our new List components already after our teaser announcement in the community group, but we are officially announcing them today! No more ListViews or DataSources, stale rows, ignored bugs, or excessive memory consumption - with the latest React Native March 2017 release candidate (0.43-rc.1) you can pick from the new suite of components what best fits your use-case, with great perf and feature sets out of the box:
For the past year, we've been working on improving performance of animations that use the Animated library. Animations are very important to create a beautiful user experience but can also be hard to do right. We want to make it easy for developers to create performant animations without having to worry about some of their code causing it to lag.
Shortly after React Native was introduced, we started releasing every two weeks to help the community adopt new features, while keeping versions stable for production use. At Facebook we had to stabilize the codebase every two weeks for the release of our production iOS apps, so we decided to release the open source versions at the same pace. Now, many of the Facebook apps ship once per week, especially on Android. Because we ship from master weekly, we need to keep it quite stable. So the bi-weekly release cadence doesn't even benefit internal contributors anymore.
We have heard from many people that there is so much work happening with React Native, it can be tough to keep track of what's going on. To help communicate what work is in progress, we are now publishing a roadmap for React Native. At a high level, this work can be broken down into three priorities:
After launching an app to the app stores, internationalization is the next step to further your audience reach. Over 20 countries and numerous people around the world use Right-to-Left (RTL) languages. Thus, making your app support RTL for them is necessary.
The React Native monthly meeting continues! This month's meeting was a bit shorter as most of our teams were busy shipping. Next month, we are at React Native EU conference in Wroclaw, Poland. Make sure to grab a ticket and see you there in person! Meanwhile, let's see what our teams are up to.
React Native is used in multiple places across multiple apps in the Facebook family including a top level tab in the main Facebook apps. Our focus for this post is a highly visible product, Marketplace. It is available in a dozen or so countries and enables users to discover products and services provided by other users.
The React Native monthly meeting continues! On this session, we were joined by Infinite Red, great minds behind Chain React, the React Native Conference. As most of the people here were presenting talks at Chain React, we pushed the meeting to a week later. Talks from the conference have been posted online and I encourage you to check them out. So, let's see what our teams are up to.
At Shoutem, we've been fortunate enough to work with React Native from its very beginnings. We decided we wanted to be part of the amazing community from day one. Soon enough, we realized it's almost impossible to keep up with the pace the community was growing and improving. That's why we decided to organize a monthly meeting where all major React Native contributors can briefly present what their efforts and plans are.
Today we’re announcing Create React Native App: a new tool that makes it significantly easier to get started with a React Native project! It’s heavily inspired by the design of Create React App and is the product of a collaboration between Facebook and Expo (formerly Exponent).
At Facebook, we often need to access deeply nested values in data structures fetched with GraphQL. On the way to accessing these deeply nested values, it is common for one or more intermediate fields to be nullable. These intermediate fields may be null for a variety of reasons, from failed privacy checks to the mere fact that null happens to be the most flexible way to represent non-fatal errors.
Many of you have started playing with some of our new List components already after our teaser announcement in the community group, but we are officially announcing them today! No more ListViews or DataSources, stale rows, ignored bugs, or excessive memory consumption - with the latest React Native March 2017 release candidate (0.43-rc.1) you can pick from the new suite of components what best fits your use-case, with great perf and feature sets out of the box:
For the past year, we've been working on improving performance of animations that use the Animated library. Animations are very important to create a beautiful user experience but can also be hard to do right. We want to make it easy for developers to create performant animations without having to worry about some of their code causing it to lag.
Shortly after React Native was introduced, we started releasing every two weeks to help the community adopt new features, while keeping versions stable for production use. At Facebook we had to stabilize the codebase every two weeks for the release of our production iOS apps, so we decided to release the open source versions at the same pace. Now, many of the Facebook apps ship once per week, especially on Android. Because we ship from master weekly, we need to keep it quite stable. So the bi-weekly release cadence doesn't even benefit internal contributors anymore.
We have heard from many people that there is so much work happening with React Native, it can be tough to keep track of what's going on. To help communicate what work is in progress, we are now publishing a roadmap for React Native. At a high level, this work can be broken down into three priorities:
Last week I had the opportunity to attend the React Native Meetup at Zynga’s San Francisco office. With around 200 people in attendance, it served as a great place to meet other developers near me that are also interested in React Native.
Part of having a great developer experience is having great documentation. A lot goes into creating good docs - the ideal documentation is concise, helpful, accurate, complete, and delightful. Recently we've been working hard to make the docs better based on your feedback, and we wanted to share some of the improvements we've made.
It's been one year since we open-sourced React Native. What started as an idea with a handful of engineers is now a framework being used by product teams across Facebook and beyond. Today at F8 we announced that Microsoft is bringing React Native to the Windows ecosystem, giving developers the potential to build React Native on Windows PC, Phone, and Xbox. It will also provide open source tools and services such as a React Native extension for Visual Studio Code and CodePush to help developers create React Native apps on the Windows platform. In addition, Samsung is building React Native for its hybrid platform, which will empower developers to build apps for millions of SmartTVs and mobile and wearable devices. We also released the Facebook SDK for React Native, which makes it easier for developers to incorporate Facebook social features like Login, Sharing, App Analytics, and Graph APIs into their apps. In one year, React Native has changed the way developers build on every major platform.
React Native allows you to build iOS and Android apps in JavaScript using React and Relay's declarative programming model. This leads to more concise, easier-to-understand code; fast iteration without a compile cycle; and easy sharing of code across multiple platforms. You can ship faster and focus on details that really matter, making your app look and feel fantastic. Optimizing performance is a big part of this. Here is the story of how we made React Native app startup twice as fast.
React Native's goal is to give you the best possible developer experience. A big part of it is the time it takes between you save a file and be able to see the changes. Our goal is to get this feedback loop to be under 1 second, even as your app grows.
With the recent launch of React on web and React Native on mobile, we've provided a new front-end framework for developers to build products. One key aspect of building a robust product is ensuring that anyone can use it, including people who have vision loss or other disabilities. The Accessibility API for React and React Native enables you to make any React-powered experience usable by someone who may use assistive technology, like a screen reader for the blind and visually impaired.
Earlier this year, we introduced React Native for iOS. React Native brings what developers are used to from React on the web — declarative self-contained UI components and fast development cycles — to the mobile platform, while retaining the speed, fidelity, and feel of native applications. Today, we're happy to release React Native for Android.
We introduced React to the world two years ago, and since then it's seen impressive growth, both inside and outside of Facebook. Today, even though no one is forced to use it, new web projects at Facebook are commonly built using React in one form or another, and it's being broadly adopted across the industry. Engineers are choosing to use React every day because it enables them to spend more time focusing on their products and less time fighting with their framework. It wasn't until we'd been building with React for a while, though, that we started to understand what makes it so powerful.
After launching an app to the app stores, internationalization is the next step to further your audience reach. Over 20 countries and numerous people around the world use Right-to-Left (RTL) languages. Thus, making your app support RTL for them is necessary.
Last week I had the opportunity to attend the React Native Meetup at Zynga’s San Francisco office. With around 200 people in attendance, it served as a great place to meet other developers near me that are also interested in React Native.
Part of having a great developer experience is having great documentation. A lot goes into creating good docs - the ideal documentation is concise, helpful, accurate, complete, and delightful. Recently we've been working hard to make the docs better based on your feedback, and we wanted to share some of the improvements we've made.
It's been one year since we open-sourced React Native. What started as an idea with a handful of engineers is now a framework being used by product teams across Facebook and beyond. Today at F8 we announced that Microsoft is bringing React Native to the Windows ecosystem, giving developers the potential to build React Native on Windows PC, Phone, and Xbox. It will also provide open source tools and services such as a React Native extension for Visual Studio Code and CodePush to help developers create React Native apps on the Windows platform. In addition, Samsung is building React Native for its hybrid platform, which will empower developers to build apps for millions of SmartTVs and mobile and wearable devices. We also released the Facebook SDK for React Native, which makes it easier for developers to incorporate Facebook social features like Login, Sharing, App Analytics, and Graph APIs into their apps. In one year, React Native has changed the way developers build on every major platform.
React Native allows you to build iOS and Android apps in JavaScript using React and Relay's declarative programming model. This leads to more concise, easier-to-understand code; fast iteration without a compile cycle; and easy sharing of code across multiple platforms. You can ship faster and focus on details that really matter, making your app look and feel fantastic. Optimizing performance is a big part of this. Here is the story of how we made React Native app startup twice as fast.
React Native's goal is to give you the best possible developer experience. A big part of it is the time it takes between you save a file and be able to see the changes. Our goal is to get this feedback loop to be under 1 second, even as your app grows.
With the recent launch of React on web and React Native on mobile, we've provided a new front-end framework for developers to build products. One key aspect of building a robust product is ensuring that anyone can use it, including people who have vision loss or other disabilities. The Accessibility API for React and React Native enables you to make any React-powered experience usable by someone who may use assistive technology, like a screen reader for the blind and visually impaired.
Earlier this year, we introduced React Native for iOS. React Native brings what developers are used to from React on the web — declarative self-contained UI components and fast development cycles — to the mobile platform, while retaining the speed, fidelity, and feel of native applications. Today, we're happy to release React Native for Android.
We introduced React to the world two years ago, and since then it's seen impressive growth, both inside and outside of Facebook. Today, even though no one is forced to use it, new web projects at Facebook are commonly built using React in one form or another, and it's being broadly adopted across the industry. Engineers are choosing to use React every day because it enables them to spend more time focusing on their products and less time fighting with their framework. It wasn't until we'd been building with React for a while, though, that we started to understand what makes it so powerful.
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.
In addition to this documentation, you might find this blog post about React Native accessibility to be useful.
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.
In addition to this documentation, you might find this blog post about React Native accessibility to be useful.
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:
Sometimes it's useful to know whether or not the device has a screen reader that is currently active. The
AccessibilityInfo API is designed for this purpose. You can use it to query the current state of the
screen reader as well as to register to be notified when the state of the screen reader changes.
Here's a small example illustrating how to use AccessibilityInfo:
classScreenReaderStatusExampleextendsReact.Component{
state ={
@@ -39,13 +39,13 @@ screen reader as well as to register to be notified when the state of the screen
</View>);}
-}
Query whether a screen reader is currently enabled. Returns a promise which
resolves to a boolean. The result is true when a screen reader is enabled
-and false otherwise.
change: Fires when the state of the screen reader changes. The argument
to the event handler is a boolean. The boolean is true when a screen
reader is enabled and false otherwise.
announcementFinished: iOS-only event. Fires when the screen reader has
finished making an announcement. The argument to the event handler is a dictionary
-with these keys:
announcement: The string announced by the screen reader.
success: A boolean indicating whether the announcement was successfully made.
Display the iOS share sheet. The options object should contain
one or both of message and url and can additionally have
a subject or excludedActivityTypes:
url (string) - a URL to share
message (string) - a message to share
subject (string) - a subject for the message
excludedActivityTypes (array) - the activities to exclude from the ActionSheet
NOTE: if url points to a local file, or is a base64-encoded
uri, the file it points to will be loaded and shared directly.
In this way, you can share images, videos, PDF files, etc.
The 'failureCallback' function takes one parameter, an error object.
The only property defined on this object is an optional stack property
-of type string.
The 'successCallback' function takes two parameters:
a boolean value signifying success or failure
a string that, in the case of success, indicates the method of sharing
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,
@@ -18,7 +18,7 @@ i.e. { cancelable: false }
This optional argument should
- be either a single-argument function or an array of buttons. If passed
- a function, it will be called when the user taps 'OK'.
If passed an array of button configurations, each button should include
- a text key, as well as optional onPress and style keys. style
- should be one of 'default', 'cancel' or 'destructive'.
This optional argument should be either a single-argument function or an array of buttons. If passed a function, it will be called when the user taps 'OK'. If passed an array of button configurations, each button should include a text key, as well as optional onPress and style keys. style should be one of 'default', 'cancel' or 'destructive'.
AlertIOS.alert('Update available','Keep your app up to date to enjoy the latest features',[{text:'Cancel', onPress:()=> console.log('Cancel Pressed'), style:'cancel'},{text:'Install', onPress:()=> console.log('Install Pressed')},],
-);
This optional argument should
- be either a single-argument function or an array of buttons. If passed
- a function, it will be called with the prompt's value when the user
- taps 'OK'.
If passed an array of button configurations, each button should include
- a text key, as well as optional onPress and style keys (see
- example). style should be one of 'default', 'cancel' or 'destructive'.
This configures the text input. One of 'plain-text',
- 'secure-text' or 'login-password'.
[defaultValue]
string
The default text in text input.
[keyboardType]
string
The keyboard type of first text field(if exists).
- One of 'default', 'email-address', 'numeric', 'phone-pad',
- 'ascii-capable', 'numbers-and-punctuation', 'url', 'number-pad',
- 'name-phone-pad', 'decimal-pad', 'twitter' or 'web-search'.
This optional argument should be either a single-argument function or an array of buttons. If passed a function, it will be called with the prompt's value when the user taps 'OK'. If passed an array of button configurations, each button should include a text key, as well as optional onPress and style keys (see example). style should be one of 'default', 'cancel' or 'destructive'.
This configures the text input. One of 'plain-text', 'secure-text' or 'login-password'.
defaultValue
string
No
The default text in text input.
keyboardType
string
No
The keyboard type of first text field(if exists). One of 'default', 'email-address', 'numeric', 'phone-pad', 'ascii-capable', 'numbers-and-punctuation', 'url', 'number-pad', 'name-phone-pad', 'decimal-pad', 'twitter' or 'web-search'.
Example with custom buttons:
AlertIOS.prompt('Enter password','Enter your password to claim your $1.5B in lottery winnings',[
@@ -37,13 +22,13 @@ cross-platform support if you don't need to create iOS-only prompts.{text:'OK', onPress: password => console.log('OK Pressed, password: '+ password)},],'secure-text'
-);
Example with the default button and a custom callback:
AlertIOS.prompt(
+);
,
Example with the default button and a custom callback:
AlertIOS.prompt('Update username',null,
text => console.log("Your username is "+text),null,'default'
-);
This page only applies to projects made with react-native init or to those made with Create React Native App which have since ejected. For more information about ejecting, please see the guide on the Create React Native App repository.
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.
This page only applies to projects made with react-native init or to those made with Create React Native App which have since ejected. For more information about ejecting, please see the guide on the Create React Native App repository.
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.
If you find that you need to push up a locally compiled React Native .aar and related files to a remote Nexus repository, you can.
Start by following the Point Gradle to your Android SDK section of this page. Once you do this, assuming you have Gradle configured properly, you can then run the following command from the root of your React Native checkout to build and package all required files:
./gradlew ReactAndroid:installArchives
This will package everything that would typically be included in the android directory of your node_modules/react-native/ installation in the root directory of your React Native checkout.
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 Running Tests.
The Animated library is designed to make animations fluid, powerful, and
easy to build and maintain. 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.
The simplest workflow for creating an animation is to create an
@@ -63,13 +63,13 @@ the following in order to map event.nativeEvent.contentOffset.x to
}}}]
- )}
Animates a value according to an analytical spring model based on
damped harmonic oscillation.
Tracks velocity state to create fluid motions as the toValue updates, and
can be chained together.
Config is an object that may have the following options.
Note that you can only define one of bounciness/speed, tension/friction, or
@@ -86,26 +86,26 @@ is at rest).
Create a new Animated value that is limited between 2 values. It uses the
difference between the last value so even if the value is far from the bounds
it will start changing when the value starts getting closer again.
(value = clamp(value + diff, min, max)).
This is useful with scroll events, for example, to show the navbar when
-scrolling up and to hide it when scrolling down.
Starts an array of animations in order, waiting for each to complete
before starting the next. If the current running animation is stopped, no
-following animations will be started.
Starts an array of animations all at the same time. By default, if one
of the animations is stopped, they will all be stopped. You can override
-this with the stopTogether flag.
Loops a given animation continuously, so that each time it reaches the
end, it resets and begins again from the start. Can specify number of
times to loop using the key iterations in the config. Will loop without
blocking the UI thread if the child animation is set to useNativeDriver: true.
In addition, loops can prevent VirtualizedList-based components from rendering
more rows while the animation is running. You can pass isInteraction: false in the
-child animation config to fix this.
Takes an array of mappings and extracts values from each arg accordingly,
then calls setValue on the mapped outputs. e.g.
onScroll={Animated.event([{nativeEvent:{contentOffset:{x:this._scrollX}}}],{listener:(event)=> console.log(event)}, // Optional async listener
@@ -115,10 +115,8 @@ then calls setValue on the mapped outputs. e.g.
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:
@@ -84,7 +84,7 @@ each of which simply take an array of animations to execute and automatically ca
]),]).start(); // start the sequence group
If one animation is stopped or interrupted, then all other animations in the group are also stopped.
Animated.parallel has a stopTogether option that can be set to false to disable this.
You can find a full list of composition methods in the Composing animations section of the Animated API reference.
App extensions let you provide custom functionality and content outside of your main app. There are different types of app extensions on iOS, and they are all covered in the App Extension Programming Guide. In this guide, we'll briefly cover how you may take advantage of app extensions on iOS.
As these extensions are loaded outside of the regular app sandbox, it's highly likely that several of these app extensions will be loaded simultaneously. As you might expect, these extensions have small memory usage limits. Keep these in mind when developing your app extensions. It's always highly recommended to test your application on an actual device, and more so when developing app extensions: too frequently, developers find that their extension works just fine in the iOS Simulator, only to get user reports that their extension is not loading on actual devices.
We highly recommend that you watch Conrad Kramer's talk on Memory Use in Extensions to learn more about this topic.
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 types of app extensions have greater memory limits than the Today widget. For instance, Custom Keyboard extensions are limited to 48 MB, and Share extensions are limited to 120 MB. Implementing such app extensions with React Native is more viable. One proof of concept example is react-native-ios-share-extension.
App extensions let you provide custom functionality and content outside of your main app. There are different types of app extensions on iOS, and they are all covered in the App Extension Programming Guide. In this guide, we'll briefly cover how you may take advantage of app extensions on iOS.
As these extensions are loaded outside of the regular app sandbox, it's highly likely that several of these app extensions will be loaded simultaneously. As you might expect, these extensions have small memory usage limits. Keep these in mind when developing your app extensions. It's always highly recommended to test your application on an actual device, and more so when developing app extensions: too frequently, developers find that their extension works just fine in the iOS Simulator, only to get user reports that their extension is not loading on actual devices.
We highly recommend that you watch Conrad Kramer's talk on Memory Use in Extensions to learn more about this topic.
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 types of app extensions have greater memory limits than the Today widget. For instance, Custom Keyboard extensions are limited to 48 MB, and Share extensions are limited to 120 MB. Implementing such app extensions with React Native is more viable. One proof of concept example is react-native-ios-share-extension.
This API only works in projects made with react-native init
@@ -17,13 +17,7 @@ for the app and then actually run the app when it's ready by invoking
AppRegistry.unmountApplicationComponentAtRootTag with the tag that was
passed into runApplication. These should always be used as a pair.
AppRegistry should be required early in the require sequence to make
sure the JS execution environment is setup before other modules are
-required.
Register a headless task. A headless task is a bit of code that runs without a UI.
-@param taskKey the key associated with this task
-@param task a promise returning function that takes some data passed from the native side as
- 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
background - The app is running in the background. The user is either
- in another app or on the home screen
inactive - This is a state that occurs when transitioning between
- foreground & background, and during periods of inactivity such as
- entering the Multitasking view or in the event of an incoming call
To see the current state, you can check AppState.currentState, which
-will be kept up-to-date. However, currentState will be null at launch
-while AppState retrieves it over the bridge.
import React,{Component}from'react'
+in another app or on the home screen
inactive - This is a state that occurs when transitioning between foreground & background, and during periods of inactivity such as entering the Multitasking view or in the event of an incoming call
To see the current state, you can check AppState.currentState, which will be kept up-to-date. However, currentState will be null at launch while AppState retrieves it over the bridge.
import React,{Component}from'react'import{AppState, Text}from'react-native'classAppStateExampleextendsComponent{
@@ -36,14 +31,8 @@ while AppState retrieves it over the bridge.
);}
-}
This example will only ever appear to say "Current state is: active" because
-the app is only visible to the user when in the active state, and the null
-state will happen only momentarily.
Add a handler to AppState changes by listening to the change event type
-and providing the handler
TODO: now that AppState is a subclass of NativeEventEmitter, we could deprecate
-addEventListener and removeEventListener and just use addListener and
-listener.remove() directly. That will be a breaking change though, as both
-the method and event names are different (addListener events are currently
-required to be globally unique).
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
-serialized dictionary and larger values in separate files. On Android,
-AsyncStorage will use either RocksDB or SQLite
-based on what is available.
The AsyncStorage JavaScript code is a simple facade that provides a clear
-JavaScript API, real Error objects, and simple non-multi functions. Each
-method in the API returns a Promise object.
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 serialized dictionary and larger values in separate files. On Android, AsyncStorage will use either RocksDB or SQLite based on what is available.
The AsyncStorage JavaScript code is a simple facade that provides a clear JavaScript API, real Error objects, and simple non-multi functions. Each method in the API returns a Promise object.
Persisting data:
try{await AsyncStorage.setItem('@MySuperStore:key','I like to save it.');}catch(error){ // Error saving data
@@ -18,21 +10,18 @@ method in the API returns a Promise object.
Persisting data:<
}}catch(error){ // Error retrieving data
-}
The following batched functions are useful for executing a lot of operations at once, allowing for native optimizations and provide the convenience of a single callback after all operations are complete.
These functions return arrays of errors, potentially one for every key. For key-specific errors, the Error object will have a key property to indicate which key caused the error.
Erases allAsyncStorage for all clients, libraries, etc. You probably
-don't want to call this; use removeItem or multiRemove to clear only
-your app's keys. Returns a Promise object.
This allows you to batch the fetching of items given an array of key
-inputs. Your callback will be invoked with an array of corresponding
-key-value pairs found:
Erases allAsyncStorage for all clients, libraries, etc. You probably don't want to call this; use removeItem or multiRemove to clear only your app's keys. Returns a Promise object.
This allows you to batch the fetching of items given an array of key inputs. Your callback will be invoked with an array of corresponding key-value pairs found:
Function that will be called with a key-value array of the results, plus an array of any key-specific errors found.
Example:
AsyncStorage.getAllKeys((err, keys)=>{
AsyncStorage.multiGet(keys,(err, stores)=>{
stores.map((result, i, store)=>{ // get at each store's key/value so you can work with it
@@ -59,19 +43,16 @@ key-value pairs found:
Call this to batch the deletion of all keys in the keys array. Returns
+a Promise object.
Parameters:
Name
Type
Required
Description
keys
Array<string>
Yes
Array of key for the items to delete.
callback
?(errors: ?Array<Error>) => void
No
Function that will be called an array of any key-specific errors found.
Example:
let keys =['k1','k2'];
AsyncStorage.multiRemove(keys,(err)=>{ // keys k1 & k2 removed, if they existed
// do most stuff after removal (if you want)
-});
Batch operation to merge in existing and new values for a given set of
keys. This assumes that the values are stringified JSON. Returns a
-Promise object.
NOTE: This is not supported by all native implementations.
Parameters:
Name and Type
Description
keyValuePairs
Array<Array<string>>
Array of key-value array for the items to merge.
[callback]
?(errors: ?Array<Error>) => void
Function that will be called with an array of any
- key-specific errors found.
Example:
+Promise object.
NOTE: This is not supported by all native implementations.
Parameters:
Name
Type
Required
Description
keyValuePairs
Array<Array<string>>
Yes
Array of key-value array for the items to merge.
callback
?(errors: ?Array<Error>) => void
No
Function that will be called with an array of any key-specific errors found.
Detect hardware button presses for back navigation.
Android: 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.
tvOS: Detect presses of the menu button on the TV remote. (Still to be implemented:
-programmatically disable menu button handling
-functionality to exit the app if there are no listeners or if none of the listeners return true.)
iOS: Not applicable.
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.
Detect hardware button presses for back navigation.
Android: 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.
tvOS: Detect presses of the menu button on the TV remote. Still to be implemented: programmatically disable menu button handling functionality to exit the app if there are no listeners or if none of the listeners return true.
iOS: Not applicable.
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:
BackHandler.addEventListener('hardwareBackPress',function(){ // this.onMainScreen and this.goBack are just examples, you need to use your own implementation here
// Typically you would use the navigator here to go to the last state.
@@ -11,7 +7,7 @@ and if one subscription returns true then subscriptions registered earlier will
returntrue;}returnfalse;
-});
This page only applies to projects made with react-native init or to those made with Create React Native App which have since ejected. For more information about ejecting, please see the guide on the Create React Native App repository.
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.
The RNTester app supports Apple TV; use the RNTester-tvOS build target to build for tvOS.
This page only applies to projects made with react-native init or to those made with Create React Native App which have since ejected. For more information about ejecting, please see the guide on the Create React Native App repository.
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.
The RNTester app supports Apple TV; use the RNTester-tvOS build target to build for tvOS.
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.
Access to touchable controls: When running on Apple TV, the native view class is RCTTVView, which has additional methods to make use of the tvOS focus engine. 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 and TouchableOpacity 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:
var TVEventHandler =require('TVEventHandler');.
@@ -38,7 +38,7 @@
componentWillUnmount(){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.
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.
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.
The user's permission is required in order to access the Camera Roll on devices running iOS 10 or later.
Add the NSPhotoLibraryUsageDescription key in your Info.plist with a string that describes how your
-app will use this data. This key will appear as Privacy - Photo Library Usage Description in Xcode.
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)
+app will use this data. This key will appear as Privacy - Photo Library Usage Description in Xcode.
Saves the photo or video to the camera roll / gallery.
On Android, the tag must be a local image or video URI, such as "file:///sdcard/img.png".
On iOS, the tag can be any image URI (including local, remote asset-library and base64 data URIs)
or a local video file URI (remote or data URIs are not supported for saving video at this time).
If the tag has a file extension of .mov or .mp4, it will be inferred as a video. Otherwise
it will be treated as a photo. To override the automatic choice, you can pass an optional
-type parameter that must be one of 'photo' or 'video'.
Returns a Promise which will resolve with the new URI.
mimeTypes : {string} : Filter by mimetype (e.g. image/jpeg).
Returns a Promise which when resolved will be of the following shape:
edges : {Array<node>} An array of node objects
node: {object} An object with the following shape:
type: {string}
group_name: {string}
image: {object} : An object with the following shape:
uri: {string}
height: {number}
width: {number}
isStored: {boolean}
timestamp: {number}
location: {object} : An object with the following shape:
latitude: {number}
longitude: {number}
altitude: {number}
heading: {number}
speed: {number}
page_info : {object} : An object with the following shape:
has_next_page: {boolean}
start_cursor: {boolean}
end_cursor: {boolean}
Loading images:
_handleButtonPress =()=>{
CameraRoll.getPhotos({
first:20,
@@ -38,7 +38,7 @@ roll of the device matching shape defined by getPhotosReturnChecker</ScrollView></View>);
-}
This is a controlled component that requires an onValueChange callback that
updates the value prop in order for the component to reflect user actions.
If the value prop is not updated, the component will continue to render
the supplied value prop instead of the expected result of any user actions.
This page only applies to projects made with react-native init or to those made with Create React Native App which have since ejected. For more information about ejecting, please see the guide on the Create React Native App repository.
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 its own internal state. We do this with properties: data is passed from a parent to its children in a top-down manner. If an ancestor component relies on the state of its descendant, one should pass down a callback to 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.
You can pass properties down to the React Native app by providing a custom implementation of ReactActivityDelegate in your main activity. This implementation should override getLaunchOptions to return a Bundle with the desired properties.
publicclassMainActivityextendsReactActivity{
+Communication between native and React Native - React Native
This page only applies to projects made with react-native init or to those made with Create React Native App which have since ejected. For more information about ejecting, please see the guide on the Create React Native App repository.
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 its own internal state. We do this with properties: data is passed from a parent to its children in a top-down manner. If an ancestor component relies on the state of its descendant, one should pass down a callback to 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.
You can pass properties down to the React Native app by providing a custom implementation of ReactActivityDelegate in your main activity. This implementation should override getLaunchOptions to return a Bundle with the desired properties.
It is fine to update properties anytime. However, updates have to be performed on the main thread. You use the getter on any thread.
There is no way to update only a few properties at a time. We suggest that you build it into your own wrapper instead.
Note:
Currently, JS functions componentWillReceiveProps and componentWillUpdateProps of the top level RN component will not be called after a prop update. However, you can access the new props in componentWillMount function.
The problem exposing properties of native components is covered in detail in this article. In short, properties that are to be reflected in JavaScript needs to be exposed as setter method annotated with @ReactProp, then just use them in React Native as if the component was an ordinary React Native component.
The main drawback of cross-language properties is that they do not support callbacks, which would allow us to handle bottom-up data bindings. Imagine you have a small RN view that you want to be removed from the native parent view as a result of a JS action. There is no way to do that with props, as the information would need to go bottom-up.
Although we have a flavor of cross-language callbacks (described here), these callbacks are not always the thing we need. The main problem is that they are not intended to be passed as properties. Rather, this mechanism allows us to trigger a native action from JS, and handle the result of that action in JS.
Other ways of cross-language interaction (events and native modules) #
As stated in the previous chapter, using properties comes with some limitations. Sometimes properties are not enough to drive the logic of our app and we need a solution that gives more flexibility. This chapter covers other communication techniques available in React Native. They can be used for internal communication (between JS and native layers in RN) as well as for external communication (between RN and the 'pure native' part of your app).
React Native enables you to perform cross-language function calls. You can execute custom native code from JS and vice versa. Unfortunately, depending on the side we are working on, we achieve the same goal in different ways. For native - we use events mechanism to schedule an execution of a handler function in JS, while for React Native we directly call methods exported by native modules.
Calling React Native functions from native (events) #
Events are described in detail in this article. Note that using events gives us no guarantees about execution time, as the event is handled on a separate thread.
Events are powerful, because they allow us to change React Native components without needing a reference to them. However, there are some pitfalls that you can fall into while using them:
As events can be sent from anywhere, they can introduce spaghetti-style dependencies into your project.
Events share namespace, which means that you may encounter some name collisions. Collisions will not be detected statically, which makes them hard to debug.
If you use several instances of the same React Native component and you want to distinguish them from the perspective of your event, you'll likely need to introduce identifiers and pass them along with events (you can use the native view's reactTag as an identifier).
Calling native functions from React Native (native modules) #
Native modules are Java classes that are available in JS. Typically one instance of each module is created per JS bridge. They can export arbitrary functions and constants to React Native. They have been covered in detail in this article.
Warning:
-All native modules share the same namespace. Watch out for name collisions when creating new ones.
This page only applies to projects made with react-native init or to those made with Create React Native App which have since ejected. For more information about ejecting, please see the guide on the Create React Native App repository.
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 its own internal state. We do this with properties: data is passed from a parent to its children in a top-down manner. If an ancestor component relies on the state of its descendant, one should pass down a callback to 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.
NSArray *imageList = @[@"http://foo.com/bar1.png",
+Communication between native and React Native - React Native
This page only applies to projects made with react-native init or to those made with Create React Native App which have since ejected. For more information about ejecting, please see the guide on the Create React Native App repository.
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 its own internal state. We do this with properties: data is passed from a parent to its children in a top-down manner. If an ancestor component relies on the state of its descendant, one should pass down a callback to 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.
NSArray *imageList = @[@"http://foo.com/bar1.png",
@"http://foo.com/bar2.png"];
NSDictionary *props = @{@"images": imageList};
@@ -73,7 +73,7 @@ Making a dimension flexible in both JS and native leads to undefined behavior. F
newFrame.size = rootView.intrinsicContentSize;
rootView.frame = newFrame;
-}
In the example we have a FlexibleSizeExampleView view that holds a root view. We create the root view, initialize it and set the delegate. The delegate will handle size updates. Then, we set the root view's size flexibility to RCTRootViewSizeFlexibilityHeight, which means that rootViewDidChangeIntrinsicSize: method will be called every time the React Native content changes its height. Finally, we set the root view's width and position. Note that we set there height as well, but it has no effect as we made the height RN-dependent.
You can checkout full source code of the example here.
It's fine to change root view's size flexibility mode dynamically. Changing flexibility mode of a root view will schedule a layout recalculation and the delegate rootViewDidChangeIntrinsicSize: method will be called once the content size is known.
Note: React Native layout calculation is performed on a special thread, while native UI view updates are done on the main thread. This may cause temporary UI inconsistencies between native and React Native. This is a known problem and our team is working on synchronizing UI updates coming from different sources.
Note: React Native does not perform any layout calculations until the root view becomes a subview of some other views. If you want to hide React Native view until its dimensions are known, add the root view as a subview and make it initially hidden (use UIView's hidden property). Then change its visibility in the delegate method.
React Native provides a number of built-in components. You will find a full list of components and APIs on the sidebar to the left. If you're not sure where to get started, take a look at the following categories:
You're not limited to the components and APIs bundled with React Native. React Native is a community of thousands of developers. If you're looking for a library that does something specific, search the npm registry for packages mentioning react-native, or check out Awesome React Native for a curated list.
React Native provides a number of built-in components. You will find a full list of components and APIs on the sidebar to the left. If you're not sure where to get started, take a look at the following categories:
You're not limited to the components and APIs bundled with React Native. React Native is a community of thousands of developers. If you're looking for a library that does something specific, search the npm registry for packages mentioning react-native, or check out Awesome React Native for a curated list.
React Native is one of Facebook's first open source projects that is both under very active development and is also being used to ship code to everybody using Facebook's mobile apps. If you're interested in contributing to React Native, hopefully this document makes the process for contributing clear.
Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please read the full text so that you can understand what actions will and will not be tolerated.
There are many ways to contribute to React Native, and many of them do not involve writing any code. Here's a few ideas to get started:
Simply start using React Native. Go through the Getting Started guide. Does everything work as expected? If not, we're always looking for improvements. Let us know by opening an issue.
Look through the open issues. Provide workarounds, ask for clarification, or suggest labels. Help triage issues.
Read through the React Native docs. If you find anything that is confusing or can be improved, you can make edits by clicking "Improve this page" at the bottom of most docs.
Browse Stack Overflow and answer questions. This will help you get familiarized with common pitfalls or misunderstandings, which can be useful when contributing updates to the documentation.
Take a look at the features requested by others in the community and consider opening a pull request if you see something you want to work on.
Contributions are very welcome. If you think you need help planning your contribution, please hop into #react-native and let people know you're looking for a mentor.
Core contributors to React Native meet monthly and post their meeting notes on the React Native blog. You can also find ad hoc discussions in the React Native Core Contributors Facebook group.
Some of the core team will be working directly on GitHub. These changes will be public from the beginning. Other changesets will come via a bridge with Facebook's internal source control. This is a necessity as it allows engineers at Facebook outside of the core team to move fast and contribute from an environment they are comfortable in.
When a change made on GitHub is approved, it will first be imported into Facebook's internal source control. The change will eventually sync back to GitHub as a single commit once it has passed all internal tests.
We will do our best to keep master in good shape, with tests passing at all times. But in order to move fast, we will make API changes that your application might not be compatible with. We will do our best to communicate these changes and version appropriately so you can lock into a specific version if need be.
To see what changes are coming and provide better feedback to React Native contributors, use the latest release candidate when possible. By the time a release candidate is released, the changes it contains will have been shipped in production Facebook apps for over two weeks.
We use GitHub Issues for our public bugs. If you would like to report a problem, take a look around and see if someone already opened an issue about it. If you a are certain this is a new, unreported bug, you can submit a bug report.
If you have questions about using React Native, the Community page list various resources that should help you get started.
When opening a new issue, always make sure to fill out the issue template. This step is very important! Not doing so may result in your issue getting closed. Don't take this personally if this happens, and feel free to open a new issue once you've gathered all the information required by the template.
One issue, one bug: Please report a single bug per issue.
Provide a Snack: The best way to get attention on your issue is to provide a reduced test case. You can use Snack to demonstrate the issue.
Provide reproduction steps: List all the steps necessary to reproduce the issue. Provide a Snack or upload a sample project to GitHub. The person reading your bug report should be able to follow these steps to reproduce your issue with minimal effort.
Try out the latest version: Verify that the issue can be reproduced locally by updating your project to use React Native from master. The bug may have already been fixed!
We're not able to provide support through GitHub Issues. If you're looking for help with your code, consider asking on Stack Overflow or reaching out to the community through other channels.
Facebook has a bounty program for the safe disclosure of security bugs. With that in mind, please do not file public issues; go through the process outlined on that page.
So you have decided to contribute code back to upstream by opening a pull request. You've invested a good chunk of time, and we appreciate it. We will do our best to work with you and get the PR looked at.
Working on your first Pull Request? You can learn how from this free video series:
We have a list of beginner friendly issues to help you get your feet wet in the React Native codebase and familiar with our contribution process. This is a great place to get started.
If you would like to request a new feature or enhancement but are not yet thinking about opening a pull request, we have a place to track feature requests.
If you intend to change the public API, or make any non-trivial changes to the implementation, we recommend filing an issue that includes [Proposal] in the title. This lets us reach an agreement on your proposal before you put significant effort into it. These types of issues should be rare. If you have been contributing to the project long enough, you will probably already have access to the React Native Core Contributors Facebook Group, where this sort of discussion is usually held.
If you're only fixing a bug, it's fine to submit a pull request right away but we still recommend to file an issue detailing what you're fixing. This is helpful in case we don't accept that specific fix but want to keep track of the issue.
All pull requests should be opened against the master branch. After opening your pull request, ensure all tests pass on Circle CI. If a test fails and you believe it is unrelated to your change, leave a comment on the pull request explaining why.
Note: It is not necessary to keep clicking Merge master to your branch on the PR page. You would want to merge master if there are conflicts or tests are failing. The Facebook-GitHub-Bot ultimately squashes all commits to a single one before merging your PR.
A good test plan has the exact commands you ran and their output, provides screenshots or videos if the pull request changes UI or updates the website.
If you've added code that should be tested, add tests!
If you've changed APIs, update the documentation.
If you've updated the docs, verify the website locally and submit screenshots if applicable (see website/README.md)
React Native is one of Facebook's first open source projects that is both under very active development and is also being used to ship code to everybody using Facebook's mobile apps. If you're interested in contributing to React Native, hopefully this document makes the process for contributing clear.
Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please read the full text so that you can understand what actions will and will not be tolerated.
There are many ways to contribute to React Native, and many of them do not involve writing any code. Here's a few ideas to get started:
Simply start using React Native. Go through the Getting Started guide. Does everything work as expected? If not, we're always looking for improvements. Let us know by opening an issue.
Look through the open issues. Provide workarounds, ask for clarification, or suggest labels. Help triage issues.
Read through the React Native docs. If you find anything that is confusing or can be improved, you can make edits by clicking "Improve this page" at the bottom of most docs.
Browse Stack Overflow and answer questions. This will help you get familiarized with common pitfalls or misunderstandings, which can be useful when contributing updates to the documentation.
Take a look at the features requested by others in the community and consider opening a pull request if you see something you want to work on.
Contributions are very welcome. If you think you need help planning your contribution, please hop into #react-native and let people know you're looking for a mentor.
Core contributors to React Native meet monthly and post their meeting notes on the React Native blog. You can also find ad hoc discussions in the React Native Core Contributors Facebook group.
Some of the core team will be working directly on GitHub. These changes will be public from the beginning. Other changesets will come via a bridge with Facebook's internal source control. This is a necessity as it allows engineers at Facebook outside of the core team to move fast and contribute from an environment they are comfortable in.
When a change made on GitHub is approved, it will first be imported into Facebook's internal source control. The change will eventually sync back to GitHub as a single commit once it has passed all internal tests.
We will do our best to keep master in good shape, with tests passing at all times. But in order to move fast, we will make API changes that your application might not be compatible with. We will do our best to communicate these changes and version appropriately so you can lock into a specific version if need be.
To see what changes are coming and provide better feedback to React Native contributors, use the latest release candidate when possible. By the time a release candidate is released, the changes it contains will have been shipped in production Facebook apps for over two weeks.
We use GitHub Issues for our public bugs. If you would like to report a problem, take a look around and see if someone already opened an issue about it. If you a are certain this is a new, unreported bug, you can submit a bug report.
If you have questions about using React Native, the Community page list various resources that should help you get started.
When opening a new issue, always make sure to fill out the issue template. This step is very important! Not doing so may result in your issue getting closed. Don't take this personally if this happens, and feel free to open a new issue once you've gathered all the information required by the template.
One issue, one bug: Please report a single bug per issue.
Provide a Snack: The best way to get attention on your issue is to provide a reduced test case. You can use Snack to demonstrate the issue.
Provide reproduction steps: List all the steps necessary to reproduce the issue. Provide a Snack or upload a sample project to GitHub. The person reading your bug report should be able to follow these steps to reproduce your issue with minimal effort.
Try out the latest version: Verify that the issue can be reproduced locally by updating your project to use React Native from master. The bug may have already been fixed!
We're not able to provide support through GitHub Issues. If you're looking for help with your code, consider asking on Stack Overflow or reaching out to the community through other channels.
Facebook has a bounty program for the safe disclosure of security bugs. With that in mind, please do not file public issues; go through the process outlined on that page.
So you have decided to contribute code back to upstream by opening a pull request. You've invested a good chunk of time, and we appreciate it. We will do our best to work with you and get the PR looked at.
Working on your first Pull Request? You can learn how from this free video series:
We have a list of beginner friendly issues to help you get your feet wet in the React Native codebase and familiar with our contribution process. This is a great place to get started.
If you would like to request a new feature or enhancement but are not yet thinking about opening a pull request, we have a place to track feature requests.
If you intend to change the public API, or make any non-trivial changes to the implementation, we recommend filing an issue that includes [Proposal] in the title. This lets us reach an agreement on your proposal before you put significant effort into it. These types of issues should be rare. If you have been contributing to the project long enough, you will probably already have access to the React Native Core Contributors Facebook Group, where this sort of discussion is usually held.
If you're only fixing a bug, it's fine to submit a pull request right away but we still recommend to file an issue detailing what you're fixing. This is helpful in case we don't accept that specific fix but want to keep track of the issue.
All pull requests should be opened against the master branch. After opening your pull request, ensure all tests pass on Circle CI. If a test fails and you believe it is unrelated to your change, leave a comment on the pull request explaining why.
Note: It is not necessary to keep clicking Merge master to your branch on the PR page. You would want to merge master if there are conflicts or tests are failing. The Facebook-GitHub-Bot ultimately squashes all commits to a single one before merging your PR.
A good test plan has the exact commands you ran and their output, provides screenshots or videos if the pull request changes UI or updates the website.
If you've added code that should be tested, add tests!
If you've changed APIs, update the documentation.
If you've updated the docs, verify the website locally and submit screenshots if applicable (see website/README.md)
This page only applies to projects made with react-native init or to those made with Create React Native App which have since ejected. For more information about ejecting, please see the guide on the Create React Native App repository.
While the built-in web view has a lot of features, it is not possible to handle every use-case in React Native. You can, however, extend the web view with native code without forking React Native or duplicating all the existing web view code.
Before you do this, you should be familiar with the concepts in native UI components. You should also familiarise yourself with the native code for web views, as you will have to use this as a reference when implementing new features—although a deep understanding is not required.
To get started, you'll need to create a subclass of ReactWebViewManager, ReactWebView, and ReactWebViewClient. In your view manager, you'll then need to override:
This page only applies to projects made with react-native init or to those made with Create React Native App which have since ejected. For more information about ejecting, please see the guide on the Create React Native App repository.
While the built-in web view has a lot of features, it is not possible to handle every use-case in React Native. You can, however, extend the web view with native code without forking React Native or duplicating all the existing web view code.
Before you do this, you should be familiar with the concepts in native UI components. You should also familiarise yourself with the native code for web views, as you will have to use this as a reference when implementing new features—although a deep understanding is not required.
To get started, you'll need to create a subclass of ReactWebViewManager, ReactWebView, and ReactWebViewClient. In your view manager, you'll then need to override:
createReactWebViewInstance
getName
addEventEmitters
@ReactModule(name = CustomWebViewManager.REACT_CLASS)publicclassCustomWebViewManagerextendsReactWebViewManager{/* This name must match what we're referring to in JS */protectedstaticfinal String REACT_CLASS ="RCTCustomWebView";
@@ -136,7 +136,7 @@
'RCTCustomWebView',
CustomWebView,
WebView.extraNativeComponentConfig
-);
If you want to add custom props to your native component, you can use nativeConfig.props on the web view.
For events, the event handler must always be set to a function. This means it isn't safe to use the event handler directly from this.props, as the user might not have provided one. The standard approach is to create a event handler in your class, and then invoking the event handler given in this.props if it exists.
If you are unsure how something should be implemented from the JS side, look at WebView.android.js in the React Native source.
If you want to add custom props to your native component, you can use nativeConfig.props on the web view.
For events, the event handler must always be set to a function. This means it isn't safe to use the event handler directly from this.props, as the user might not have provided one. The standard approach is to create a event handler in your class, and then invoking the event handler given in this.props if it exists.
If you are unsure how something should be implemented from the JS side, look at WebView.android.js in the React Native source.
This page only applies to projects made with react-native init or to those made with Create React Native App which have since ejected. For more information about ejecting, please see the guide on the Create React Native App repository.
While the built-in web view has a lot of features, it is not possible to handle every use-case in React Native. You can, however, extend the web view with native code without forking React Native or duplicating all the existing web view code.
Before you do this, you should be familiar with the concepts in native UI components. You should also familiarise yourself with the native code for web views, as you will have to use this as a reference when implementing new features—although a deep understanding is not required.
This page only applies to projects made with react-native init or to those made with Create React Native App which have since ejected. For more information about ejecting, please see the guide on the Create React Native App repository.
While the built-in web view has a lot of features, it is not possible to handle every use-case in React Native. You can, however, extend the web view with native code without forking React Native or duplicating all the existing web view code.
Before you do this, you should be familiar with the concepts in native UI components. You should also familiarise yourself with the native code for web views, as you will have to use this as a reference when implementing new features—although a deep understanding is not required.
try{const{action, year, month, day}=await DatePickerAndroid.open({ // Use `new Date()` for current date.
// May 25 2020. Month 0 is January.
@@ -9,11 +9,11 @@
}}catch({code, message}){
console.warn('Cannot open date picker', message);
-}
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) - maximum 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
-when using the minDate and maxDate options.
Use DatePickerIOS to render a date/time picker (selector) on iOS. This is
a controlled component, so you must hook in to the onDateChange callback
and update the date prop in order for the component to update, otherwise
the user's change will be reverted immediately to reflect props.date as the
-source of truth.
By default, the date picker will use the device's timezone. With this
parameter, it is possible to force a certain timezone offset. For
-instance, to show times in Pacific Standard Time, pass -7 * 60.
React Native supports a few keyboard shortcuts in the iOS Simulator. They are described below. To enable them, open the Hardware menu, select Keyboard, and make sure that "Connect Hardware Keyboard" is checked.
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 ⌘D keyboard shortcut when your app is running in the iOS Simulator, or ⌘M when running in an Android emulator. Alternatively for Android, you can run the command adb shell input keyevent 82 to open the dev menu (82 being the Menu key code).
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 ⌘R in the iOS Simulator, or tap R twice on Android emulators.
You can speed up your development times by having your app reload automatically any time your code changes. Automatic reloading can be enabled by selecting "Enable Live Reload" from the Developer Menu.
You may even go a step further and keep your app running as new versions of your files are injected into the JavaScript bundle automatically by enabling Hot Reloading from the Developer Menu. This will allow you to persist the app's state through reloads.
There are some instances where hot reloading cannot be implemented perfectly. If you run into any issues, use a full reload to reset your app.
You will need to rebuild your app for changes to take effect in certain situations:
You have added new resources to your native app's bundle, such as an image in Images.xcassets on iOS or the res/drawable folder on Android.
You have modified native code (Objective-C/Swift on iOS or Java/C++ on Android).
In-app errors 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: ...'];.
In CI/Xcode, YellowBoxes can also be disabled by setting the IS_TESTING environment variable.
RedBoxes and YellowBoxes are automatically disabled in release (production) builds.
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 (⌘⌥I on macOS, CtrlShiftI on Windows). You may also want to enable Pause On Caught Exceptions for a better debugging experience.
Note: the React Developer Tools Chrome extension does not work with React Native, but you can use its standalone version instead. Read this section to learn how.
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.
Now run react-devtools from the terminal to launch the standalone DevTools app:
react-devtools
It should connect to your simulator within a few seconds.
Note: if you prefer to avoid global installations, you can add react-devtools as a project dependency. Add the react-devtools package to your project using npm install --save-dev react-devtools, then add "react-devtools": "react-devtools" to the scripts section in your package.json, and then run npm run react-devtools from your project folder to open the DevTools.
Open the in-app developer menu and choose "Show Inspector". It will bring up an overlay that lets you tap on any UI element and see information about it:
However, when react-devtools is running, Inspector will enter a special collapsed mode, and instead use the DevTools as primary UI. In this mode, clicking on something in the simulator will bring up the relevant components in the DevTools:
You can choose "Hide Inspector" in the same menu to exit this mode.
When debugging JavaScript in Chrome, you can inspect the props and state of the React components in the browser console.
First, follow the instructions for debugging in Chrome to open the Chrome console.
Make sure that the dropdown in the top left corner of the Chrome console says debuggerWorker.js. This step is essential.
Then select a React component in React DevTools. There is a search box at the top that helps you find one by name. As soon as you select it, it will be available as $r in the Chrome console, letting you inspect its props, state, and instance properties.
React Native supports a few keyboard shortcuts in the iOS Simulator. They are described below. To enable them, open the Hardware menu, select Keyboard, and make sure that "Connect Hardware Keyboard" is checked.
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 ⌘D keyboard shortcut when your app is running in the iOS Simulator, or ⌘M when running in an Android emulator. Alternatively for Android, you can run the command adb shell input keyevent 82 to open the dev menu (82 being the Menu key code).
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 ⌘R in the iOS Simulator, or tap R twice on Android emulators.
You can speed up your development times by having your app reload automatically any time your code changes. Automatic reloading can be enabled by selecting "Enable Live Reload" from the Developer Menu.
You may even go a step further and keep your app running as new versions of your files are injected into the JavaScript bundle automatically by enabling Hot Reloading from the Developer Menu. This will allow you to persist the app's state through reloads.
There are some instances where hot reloading cannot be implemented perfectly. If you run into any issues, use a full reload to reset your app.
You will need to rebuild your app for changes to take effect in certain situations:
You have added new resources to your native app's bundle, such as an image in Images.xcassets on iOS or the res/drawable folder on Android.
You have modified native code (Objective-C/Swift on iOS or Java/C++ on Android).
In-app errors 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: ...'];.
In CI/Xcode, YellowBoxes can also be disabled by setting the IS_TESTING environment variable.
RedBoxes and YellowBoxes are automatically disabled in release (production) builds.
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 (⌘⌥I on macOS, CtrlShiftI on Windows). You may also want to enable Pause On Caught Exceptions for a better debugging experience.
Note: the React Developer Tools Chrome extension does not work with React Native, but you can use its standalone version instead. Read this section to learn how.
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.
Now run react-devtools from the terminal to launch the standalone DevTools app:
react-devtools
It should connect to your simulator within a few seconds.
Note: if you prefer to avoid global installations, you can add react-devtools as a project dependency. Add the react-devtools package to your project using npm install --save-dev react-devtools, then add "react-devtools": "react-devtools" to the scripts section in your package.json, and then run npm run react-devtools from your project folder to open the DevTools.
Open the in-app developer menu and choose "Show Inspector". It will bring up an overlay that lets you tap on any UI element and see information about it:
However, when react-devtools is running, Inspector will enter a special collapsed mode, and instead use the DevTools as primary UI. In this mode, clicking on something in the simulator will bring up the relevant components in the DevTools:
You can choose "Hide Inspector" in the same menu to exit this mode.
When debugging JavaScript in Chrome, you can inspect the props and state of the React components in the browser console.
First, follow the instructions for debugging in Chrome to open the Chrome console.
Make sure that the dropdown in the top left corner of the Chrome console says debuggerWorker.js. This step is essential.
Then select a React component in React DevTools. There is a search box at the top that helps you find one by name. As soon as you select it, it will be available as $r in the Chrome console, letting you inspect its props, state, and instance properties.
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.
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');
change: Fires when a property within the Dimensions object changes. The argument
to the event handler is an object with window and screen properties whose values
are the same as the return values of Dimensions.get('window') and
-Dimensions.get('screen'), respectively.
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
@@ -150,7 +150,7 @@ ignored and overridden.
The methods described here are available on most of the default components provided by React Native. Note, however, that they are not available on composite components that aren't directly backed by a native view. This will generally include most components that you define in your own app.
Determines the location on screen, width, and height of the given view and returns the values via an async callback. If successful, the callback will be called with the following arguments:
x
y
width
height
pageX
pageY
Note that these measurements are not available until after the rendering has been completed in native. If you need the measurements as soon as possible, consider using the onLayout prop instead.
Determines the location of the given view in the window and returns the values via an async callback. If the React root view is embedded in another native view, this will give you the absolute coordinates. If successful, the callback will be called with the following arguments:
Like measure(), but measures the view relative an ancestor, specified as relativeToNativeNode. This means that the returned x, y are relative to the origin x, y of the ancestor view.
As always, to obtain a native node handle for a component, you can use ReactNative.findNodeHandle(component).
React component that wraps the platform DrawerLayout (Android only). The
Drawer (typically used for navigation) is rendered with renderNavigationView
and direct children are the main view (where your content goes). The navigation
view is initially not visible on the screen, but can be pulled in from the
@@ -20,24 +20,24 @@ be set by the drawerWidth prop.
Determines whether the keyboard gets dismissed in response to a drag.
+ - 'none' (the default), drags do not dismiss the keyboard.
+ - 'on-drag', the keyboard is dismissed when a drag begins.
Specifies the lock mode of the drawer. The drawer can be locked in 3 states:
- unlocked (default), meaning that the drawer will respond (open/close) to touch gestures.
- locked-closed, meaning that the drawer will stay closed and not respond to gestures.
- locked-open, meaning that the drawer will stay opened and not respond to gestures.
-The drawer may still be opened and closed programmatically (openDrawer/closeDrawer).
Determines whether the keyboard gets dismissed in response to a drag.
- - 'none' (the default), drags do not dismiss the keyboard.
- - 'on-drag', the keyboard is dismissed when a drag begins.
Function called when the drawer state has changed. The drawer can be in 3 states:
+The drawer may still be opened and closed programmatically (openDrawer/closeDrawer).
Function called when the drawer state has changed. The drawer can be in 3 states:
- idle, meaning there is no interaction with the navigation view happening at the time
- dragging, meaning there is currently an interaction with the navigation view
- settling, meaning that there was an interaction with the navigation view, and the
-navigation view is now finishing its closing or opening animation
Make the drawer take the entire screen and draw the background of the
status bar to allow it to open over the status bar. It will only have an
-effect on API 21+.
A simple elastic interaction, similar to a spring oscillating back and
forth.
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.
More complex, multi-select example demonstrating PureComponent usage for perf optimization and avoiding bugs.
By binding the onPressItem handler, the props will remain === and PureComponent will
prevent wasteful re-renders unless the actual id, selected, or title props change, even
if the components rendered in MyListItem did not have such optimizations.
By passing extraData={this.state} to FlatList we make sure FlatList itself will re-render
when the state.selected changes. Without setting this prop, FlatList would not know it
@@ -59,23 +59,34 @@ not show any changes.
keyExtractor tells the list to use th
/>);}
-}
This is a convenience wrapper around <VirtualizedList>,
-and thus inherits its props (as well as those of ScrollView) that aren't explicitly listed
-here, along with the following caveats:
Internal state is not preserved when content scrolls out of the render window. Make sure all
-your data is captured in the item data or external stores like Flux, Redux, or Relay.
This is a PureComponent which means that it will not re-render if props remain shallow-
-equal. Make sure that everything your renderItem function depends on is passed as a prop
-(e.g. extraData) that is not === after updates, otherwise your UI may not update on
-changes. This includes the data prop and parent component state.
In order to constrain memory and enable smooth scrolling, content is rendered asynchronously
-offscreen. This means it's possible to scroll faster than the fill rate ands momentarily see
-blank content. This is a tradeoff that can be adjusted to suit the needs of each application,
-and we are working on improving it behind the scenes.
By default, the list looks for a key prop on each item and uses that for the React key.
-Alternatively, you can provide a custom keyExtractor prop.
Also inherits ScrollView Props, unless it is nested in another FlatList of same orientation.
Scrolls to the item at the specified index such that it is positioned in the viewable area
+}
This is a convenience wrapper around VirtualizedList, and thus inherits its props (as well as those of ScrollView) that aren't explicitly listed here, along with the following caveats:
Internal state is not preserved when content scrolls out of the render window. Make sure all your data is captured in the item data or external stores like Flux, Redux, or Relay.
This is a PureComponent which means that it will not re-render if props remain shallow- equal. Make sure that everything your renderItem function depends on is passed as a prop (e.g. extraData) that is not === after updates, otherwise your UI may not update on changes. This includes the data prop and parent component state.
In order to constrain memory and enable smooth scrolling, content is rendered asynchronously offscreen. This means it's possible to scroll faster than the fill rate ands momentarily see blank content. This is a tradeoff that can be adjusted to suit the needs of each application, and we are working on improving it behind the scenes.
By default, the list looks for a key prop on each item and uses that for the React key. Alternatively, you can provide a custom keyExtractor prop.
Also inherits ScrollView props, unless it is nested in another FlatList of same orientation.
Takes an item from data and renders it into the list.
Provides additional metadata like index if you need it, as well as a more generic separators.updateProps function which let's you set whatever props you want to change the rendering of either the leading separator or trailing separator in case the more common highlight and unhighlight (which set the highlighted: boolean prop) are insufficient for your use case.
Rendered in between each item, but not at the top or bottom. By default, highlighted and leadingItem props are provided. renderItem provides separators.highlight/unhighlight which will update the highlighted prop, but you can also add custom props with separators.updateProps.
A marker property for telling the list to re-render (since it implements PureComponent). If any of your renderItem, Header, Footer, etc. functions depend on anything outside of the data prop, stick it here and treat it immutably.
getItemLayout is an optional optimization that let us skip measurement of dynamic content if you know the height of items a priori. getItemLayout is the most efficient, and is easy to use if you have fixed height items, for example:
Adding getItemLayout can be a great performance boost for lists of several hundred items. Remember to include separator length (height or width) in your offset calculation if you specify ItemSeparatorComponent.
How many items to render in the initial batch. This should be enough to fill the screen but not much more. Note these items will never be unmounted as part of the windowed rendering in order to improve perceived performance of scroll-to-top actions.
Instead of starting at the top with the first item, start at initialScrollIndex. This disables the "scroll to top" optimization that keeps the first initialNumToRender items always rendered and immediately renders the items starting at this initial index. Requires getItemLayout to be implemented.
Used to extract a unique key for a given item at the specified index. Key is used for caching and as the react key to track item re-ordering. The default extractor checks item.key, then falls back to using the index, like React does.
Multiple columns can only be rendered with horizontal={false} and will zig-zag like a flexWrap layout. Items should all be the same height - masonry layouts are not supported.
How far from the end (in units of visible length of the list) the bottom edge of the list must be from the end of the content to trigger the onEndReached callback. Thus a value of 0.5 will trigger onEndReached when the end of the content is within half the visible length of the list.
List of ViewabilityConfig/onViewableItemsChanged pairs. A specific onViewableItemsChanged will be called when its corresponding ViewabilityConfig's conditions are met. See ViewabilityHelper.js for flow type and further documentation.
Scrolls to the item at the specified index such that it is positioned in the viewable area
such that viewPosition 0 places it at the top, 1 at the bottom, and 0.5 centered in the
middle. viewOffset is a fixed number of pixels to offset the final target position.
Note: cannot scroll to locations outside the render window without specifying the
-getItemLayout prop.
Tells the list an interaction has occurred, which should trigger viewability calculations, e.g.
if waitForInteractions is true and the user has not scrolled. This is typically called by
-taps on items or by navigation actions.
A component can specify the layout of its children using the flexbox algorithm. Flexbox is designed to provide a consistent layout on different screen sizes.
You will normally use a combination of flexDirection, alignItems, and justifyContent to achieve the right layout.
Flexbox works the same way in React Native as it does in CSS on the web, with a few exceptions. The defaults are different, with flexDirection defaulting to column instead of row, and the flex parameter 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.
import React,{ Component }from'react';
+Layout with Flexbox - React Native
A component can specify the layout of its children using the flexbox algorithm. Flexbox is designed to provide a consistent layout on different screen sizes.
You will normally use a combination of flexDirection, alignItems, and justifyContent to achieve the right layout.
Flexbox works the same way in React Native as it does in CSS on the web, with a few exceptions. The defaults are different, with flexDirection defaulting to column instead of row, and the flex parameter 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.
import React,{ Component }from'react';import{ AppRegistry, View }from'react-native';exportdefaultclassFlexDirectionBasicsextendsComponent{
@@ -61,7 +61,7 @@
};
// skip this line if using Create React Native App
-AppRegistry.registerComponent('AwesomeProject',()=> AlignItemsBasics);
Request suitable Location permission based on the key configured on pList.
If NSLocationAlwaysUsageDescription is set, it will request Always authorization,
although if NSLocationWhenInUseUsageDescription is set, it will request InUse
-authorization.
Invokes the success callback once with the latest location info. Supported
options: timeout (ms), maximumAge (ms), enableHighAccuracy (bool)
On Android, if the location is cached this can return almost immediately,
-or it will request an update which might take a while.
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.
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 happening
View.props.onResponderReject: (evt) => {} - Something else is the responder right now and will not release it
If the view is responding, the following handlers can be called:
View.props.onResponderMove: (evt) => {} - The user is moving their finger
View.props.onResponderRelease: (evt) => {} - Fired at the end of the touch, ie "touchUp"
View.props.onResponderTerminationRequest: (evt) => true - Something else wants to become responder. Should this view release the responder? Returning true allows release
View.props.onResponderTerminate: (evt) => {} - The responder has been taken from the View. Might be taken by other views after a call to onResponderTerminationRequest, or might be taken by the OS without asking (happens with control center/ notification center on iOS)
evt is a synthetic touch event with the following form:
nativeEvent
changedTouches - Array of all touch events that have changed since the last event
identifier - The ID of the touch
locationX - The X position of the touch, relative to the element
locationY - The Y position of the touch, relative to the element
pageX - The X position of the touch, relative to the root element
pageY - The Y position of the touch, relative to the root element
target - The node id of the element receiving the touch event
timestamp - A time identifier for the touch, useful for velocity calculation
touches - Array of all current touches on the screen
onStartShouldSetResponder and onMoveShouldSetResponder are called with a bubbling pattern, where the deepest node is called first. That means that the deepest component will become responder when multiple Views return true for *ShouldSetResponder handlers. This is desirable in most cases, because it makes sure all controls and buttons are usable.
However, sometimes a parent will want to make sure that it becomes responder. This can be handled by using the capture phase. Before the responder system bubbles up from the deepest component, it will do a capture phase, firing on*ShouldSetResponderCapture. So if a parent View wants to prevent the child from becoming responder on a touch start, it should have a onStartShouldSetResponderCapture handler which returns true.
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.
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 happening
View.props.onResponderReject: (evt) => {} - Something else is the responder right now and will not release it
If the view is responding, the following handlers can be called:
View.props.onResponderMove: (evt) => {} - The user is moving their finger
View.props.onResponderRelease: (evt) => {} - Fired at the end of the touch, ie "touchUp"
View.props.onResponderTerminationRequest: (evt) => true - Something else wants to become responder. Should this view release the responder? Returning true allows release
View.props.onResponderTerminate: (evt) => {} - The responder has been taken from the View. Might be taken by other views after a call to onResponderTerminationRequest, or might be taken by the OS without asking (happens with control center/ notification center on iOS)
evt is a synthetic touch event with the following form:
nativeEvent
changedTouches - Array of all touch events that have changed since the last event
identifier - The ID of the touch
locationX - The X position of the touch, relative to the element
locationY - The Y position of the touch, relative to the element
pageX - The X position of the touch, relative to the root element
pageY - The Y position of the touch, relative to the root element
target - The node id of the element receiving the touch event
timestamp - A time identifier for the touch, useful for velocity calculation
touches - Array of all current touches on the screen
onStartShouldSetResponder and onMoveShouldSetResponder are called with a bubbling pattern, where the deepest node is called first. That means that the deepest component will become responder when multiple Views return true for *ShouldSetResponder handlers. This is desirable in most cases, because it makes sure all controls and buttons are usable.
However, sometimes a parent will want to make sure that it becomes responder. This can be handled by using the capture phase. Before the responder system bubbles up from the deepest component, it will do a capture phase, firing on*ShouldSetResponderCapture. So if a parent View wants to prevent the child from becoming responder on a touch start, it should have a onStartShouldSetResponderCapture handler which returns true.