diff --git a/blog/2016/03/24/introducing-hot-reloading.html b/blog/2016/03/24/introducing-hot-reloading.html index 1d62b5cd2d7..e044162e275 100644 --- a/blog/2016/03/24/introducing-hot-reloading.html +++ b/blog/2016/03/24/introducing-hot-reloading.html @@ -69,7 +69,7 @@ export default function } return store; -};

When you change a reducer, the code to accept that reducer will be sent to the client. Then the client will realize that the reducer doesn't know how to accept itself, so it will look for all the modules that refer it and try to accept them. Eventually, the flow will get to the single store, the configureStore module, which will accept the HMR update.

Conclusion #

If you are interested in helping making hot reloading better, I encourage you to read Dan Abramov's post around the future of hot reloading and to contribute. For example, Johny Days is going to make it work with multiple connected clients. We're relying on you all to maintain and improve this feature.

With React Native, we have the opportunity to rethink the way we build apps in order to make it a great developer experience. Hot reloading is only one piece of the puzzle, what other crazy hacks can we do to make it better?

React Native Blog
Stay up-to-date with the latest React Native news and events.

San Francisco Meetup Recap

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.

I was particularly interested in learning more about how React and React Native are used at companies like Zynga, Netflix, and Airbnb. The agenda for the night would be as follows:

  • Rapid Prototyping in React
  • Designing APIs for React Native
  • Bridging the Gap: Using React Native in Existing Codebases

But first, the event started off with a quick introduction and a brief recap of recent news:

If one of these meetups is held near you, I highly recommend attending!

Rapid Prototyping in React at Zynga #

The first round of news was followed by a quick introduction by Zynga, our hosts for the evening. Abhishek Chadha talked about how they use React to quickly prototype new experiences on mobile, demoing a quick prototype of a Draw Something-like app. They use a similar approach as React Native, providing access to native APIs via a bridge. This was demonstrated when Abhishek used the device's camera to snap a photo of the audience and then drew a hat on someone's head.

Designing APIs for React Native at Netflix #

Up next, the first featured talk of the evening. Clarence Leung, Senior Software Engineer at Netflix, presented his talk on Designing APIs for React Native. First he noted the two main types of libraries one may work on: components such as tab bars and date pickers, and libraries that provide access to native services such as the camera roll or in-app payments. There are two ways one may approach when building a library for use in React Native:

  • Provide platform-specific components
  • A cross-platform library with a similar API for both iOS and Android

Each approach has its own considerations, and it’s up to you to determine what works best for your needs.

Approach #1

As an example of platform-specific components, Clarence talked about the DatePickerIOS and DatePickerAndroid from core React Native. On iOS, date pickers are rendered as part of the UI and can be easily embedded in an existing view, while date pickers on Android are presented modally. It makes sense to provide separate components in this case.

Approach #2

Photo pickers, on the other hand, are treated similarly on iOS and Android. There are some slight differences — Android does not group photos into folders like iOS does with Selfies, for example — but those are easily handled using if statements and the Platform component.

Regardless of which approach you settle on, it’s a good idea to minimize the API surface and build app-specific libraries. For example, iOS’s In-App Purchase framework supports one-time, consumable purchases, as well as renewable subscriptions. If your app will only need to support consumable purchases, you may get away with dropping support for subscriptions in your cross-platform library.

There was a brief Q&A session at the end of Clarence’s talk. One of the interesting tid bits that came out of it was that around 80% of the React Native code written for these libraries at Netflix is shared across both iOS and Android.

Bridging the Gap, Using React Native in Existing Codebases #

The final talk of the night was by Leland Richardson from Airbnb. The talk was focused on the use of React Native in existing codebases. I already know how easy it is to write a new app from scratch using React Native, so I was very interested to hear about Airbnb’s experience adopting React Native in their existing native apps.

Leland started off by talking about greenfield apps versus brownfield apps. Greenfield means to start a project without the need to consider any prior work. This is in contrast to brownfield projects where you need to take into account the existing project’s requirements, development processes, and all of the teams various needs.

When you’re working on a greenfield app, the React Native CLI sets up a single repository for both iOS and Android and everything just works. The first challenge against using React Native at Airbnb was the fact that the iOS and Android app each had their own repository. Multi-repo companies have some hurdles to get past before they can adopt React Native.

To get around this, Airbnb first set up a new repo for the React Native codebase. They used their continuous integration servers to mirror the iOS and Android repos into this new repo. After tests are run and the bundle is built, the build artifacts are synced back to the iOS and Android repos. This allows the mobile engineers to work on native code without altering their development enviroment. Mobile engineers don't need to install npm, run the packager, or remember to build the JavaScript bundle. The engineers writing actual React Native code do not have to worry about syncing their code across iOS and Android, as they work on the React Native repository directly.

This does come with some drawbacks, mainly they could not ship atomic updates. Changes that require a combination of native and JavaScript code would require three separate pull requests, all of which had to be carefully landed. In order to avoid conflicts, CI will fail to land changes back to the iOS and Android repos if master has changed since the build started. This would cause long delays during high commit frequency days (such as when new releases are cut).

Airbnb has since moved to a mono repo approach. Fortunately this was already under consideration, and once the iOS and Android teams became comfortable with using React Native they were happy to accelerate the move towards the mono repo.

This has solved most of the issues they had with the split repo approach. Leland did note that this does cause a higher strain on the version control servers, which may be an issue for smaller companies.

The Navigation Problem #

The second half of Leland's talk focused on a topic that is dear to me: the Navigation problem in React Native. He talked about the abundance of navigation libraries in React Native, both first party and third party. NavigationExperimental was mentioned as something that seemed promising, but ended up not being well suited for their use case.

In fact, none of the existing navigation libraries seem to work well for brownfield apps. A brownfield app requires that the navigation state be fully owned by the native app. For example, if a user’s session expires while a React Native view is being presented, the native app should be able to take over and present a login screen as needed.

Airbnb also wanted to avoid replacing native navigation bars with JavaScript versions as part of a transition, as the effect could be jarring. Initially they limited themselves to modally presented views, but this obviously presented a problem when it came to adopting React Native more widely within their apps.

They decided that they needed their own library. The library is called airbnb-navigation. The library has not yet being open sourced as it is strongly tied to Airbnb’s codebase, but it is something they’d like to release by the end of the year.

I won’t go into much detail into the library’s API, but here are some of the key takeaways:

  • One must preregister scenes ahead of time
  • Each scene is displayed within its own RCTRootView. They are presented natively on each platform (e.g. UINavigationControllers are used on iOS).
  • The main ScrollView in a scene should be wrapped in a ScrollScene component. Doing so allows you to take advantage of native behaviors such as tapping on the status bar to scroll to the top on iOS.
  • Transitions between scenes are handled natively, no need to worry about performance.
  • The Android back button is automatically supported.
  • They can take advantage of View Controller based navigation bar styling via a Navigator.Config UI-less component.

There’s also some considerations to keep in mind:

  • The navigation bar is not easily customized in JavaScript, as it is a native component. This is intentional, as using native navigation bars is a hard requirement for this type of library.
  • ScreenProps must be serialized/de-serialized whenever they're sent through the bridge, so care must be taken if sending too much data here.
  • Navigation state is owned by the native app (also a hard requirement for the library), so things like Redux cannot manipulate navigation state.

Leland's talk was also followed by a Q&A session. Overall, Airbnb is satisfied with React Native. They’re interested in using Code Push to fix any issues without going through the App Store, and their engineers love Live Reload, as they don't have to wait for the native app to be rebuilt after every minor change.

Closing Remarks #

The event ended with some additional React Native news:

Meetups provide a good opportunity to meet and learn from other developers in the community. I'm looking forward to attending more React Native meetups in the future. If you make it up to one of these, please look out for me and let me know how we can make React Native work better for you!

React Native Blog
Stay up-to-date with the latest React Native news and events.

San Francisco Meetup Recap

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.

I was particularly interested in learning more about how React and React Native are used at companies like Zynga, Netflix, and Airbnb. The agenda for the night would be as follows:

  • Rapid Prototyping in React
  • Designing APIs for React Native
  • Bridging the Gap: Using React Native in Existing Codebases

But first, the event started off with a quick introduction and a brief recap of recent news:

If one of these meetups is held near you, I highly recommend attending!

Rapid Prototyping in React at Zynga #

The first round of news was followed by a quick introduction by Zynga, our hosts for the evening. Abhishek Chadha talked about how they use React to quickly prototype new experiences on mobile, demoing a quick prototype of a Draw Something-like app. They use a similar approach as React Native, providing access to native APIs via a bridge. This was demonstrated when Abhishek used the device's camera to snap a photo of the audience and then drew a hat on someone's head.

Designing APIs for React Native at Netflix #

Up next, the first featured talk of the evening. Clarence Leung, Senior Software Engineer at Netflix, presented his talk on Designing APIs for React Native. First he noted the two main types of libraries one may work on: components such as tab bars and date pickers, and libraries that provide access to native services such as the camera roll or in-app payments. There are two ways one may approach when building a library for use in React Native:

  • Provide platform-specific components
  • A cross-platform library with a similar API for both iOS and Android

Each approach has its own considerations, and it’s up to you to determine what works best for your needs.

Approach #1

As an example of platform-specific components, Clarence talked about the DatePickerIOS and DatePickerAndroid from core React Native. On iOS, date pickers are rendered as part of the UI and can be easily embedded in an existing view, while date pickers on Android are presented modally. It makes sense to provide separate components in this case.

Approach #2

Photo pickers, on the other hand, are treated similarly on iOS and Android. There are some slight differences — Android does not group photos into folders like iOS does with Selfies, for example — but those are easily handled using if statements and the Platform component.

Regardless of which approach you settle on, it’s a good idea to minimize the API surface and build app-specific libraries. For example, iOS’s In-App Purchase framework supports one-time, consumable purchases, as well as renewable subscriptions. If your app will only need to support consumable purchases, you may get away with dropping support for subscriptions in your cross-platform library.

There was a brief Q&A session at the end of Clarence’s talk. One of the interesting tid bits that came out of it was that around 80% of the React Native code written for these libraries at Netflix is shared across both iOS and Android.

Bridging the Gap, Using React Native in Existing Codebases #

The final talk of the night was by Leland Richardson from Airbnb. The talk was focused on the use of React Native in existing codebases. I already know how easy it is to write a new app from scratch using React Native, so I was very interested to hear about Airbnb’s experience adopting React Native in their existing native apps.

Leland started off by talking about greenfield apps versus brownfield apps. Greenfield means to start a project without the need to consider any prior work. This is in contrast to brownfield projects where you need to take into account the existing project’s requirements, development processes, and all of the teams various needs.

When you’re working on a greenfield app, the React Native CLI sets up a single repository for both iOS and Android and everything just works. The first challenge against using React Native at Airbnb was the fact that the iOS and Android app each had their own repository. Multi-repo companies have some hurdles to get past before they can adopt React Native.

To get around this, Airbnb first set up a new repo for the React Native codebase. They used their continuous integration servers to mirror the iOS and Android repos into this new repo. After tests are run and the bundle is built, the build artifacts are synced back to the iOS and Android repos. This allows the mobile engineers to work on native code without altering their development enviroment. Mobile engineers don't need to install npm, run the packager, or remember to build the JavaScript bundle. The engineers writing actual React Native code do not have to worry about syncing their code across iOS and Android, as they work on the React Native repository directly.

This does come with some drawbacks, mainly they could not ship atomic updates. Changes that require a combination of native and JavaScript code would require three separate pull requests, all of which had to be carefully landed. In order to avoid conflicts, CI will fail to land changes back to the iOS and Android repos if master has changed since the build started. This would cause long delays during high commit frequency days (such as when new releases are cut).

Airbnb has since moved to a mono repo approach. Fortunately this was already under consideration, and once the iOS and Android teams became comfortable with using React Native they were happy to accelerate the move towards the mono repo.

This has solved most of the issues they had with the split repo approach. Leland did note that this does cause a higher strain on the version control servers, which may be an issue for smaller companies.

The Navigation Problem #

The second half of Leland's talk focused on a topic that is dear to me: the Navigation problem in React Native. He talked about the abundance of navigation libraries in React Native, both first party and third party. NavigationExperimental was mentioned as something that seemed promising, but ended up not being well suited for their use case.

In fact, none of the existing navigation libraries seem to work well for brownfield apps. A brownfield app requires that the navigation state be fully owned by the native app. For example, if a user’s session expires while a React Native view is being presented, the native app should be able to take over and present a login screen as needed.

Airbnb also wanted to avoid replacing native navigation bars with JavaScript versions as part of a transition, as the effect could be jarring. Initially they limited themselves to modally presented views, but this obviously presented a problem when it came to adopting React Native more widely within their apps.

They decided that they needed their own library. The library is called airbnb-navigation. The library has not yet being open sourced as it is strongly tied to Airbnb’s codebase, but it is something they’d like to release by the end of the year.

I won’t go into much detail into the library’s API, but here are some of the key takeaways:

  • One must preregister scenes ahead of time
  • Each scene is displayed within its own RCTRootView. They are presented natively on each platform (e.g. UINavigationControllers are used on iOS).
  • The main ScrollView in a scene should be wrapped in a ScrollScene component. Doing so allows you to take advantage of native behaviors such as tapping on the status bar to scroll to the top on iOS.
  • Transitions between scenes are handled natively, no need to worry about performance.
  • The Android back button is automatically supported.
  • They can take advantage of View Controller based navigation bar styling via a Navigator.Config UI-less component.

There’s also some considerations to keep in mind:

  • The navigation bar is not easily customized in JavaScript, as it is a native component. This is intentional, as using native navigation bars is a hard requirement for this type of library.
  • ScreenProps must be serialized/de-serialized whenever they're sent through the bridge, so care must be taken if sending too much data here.
  • Navigation state is owned by the native app (also a hard requirement for the library), so things like Redux cannot manipulate navigation state.

Leland's talk was also followed by a Q&A session. Overall, Airbnb is satisfied with React Native. They’re interested in using Code Push to fix any issues without going through the App Store, and their engineers love Live Reload, as they don't have to wait for the native app to be rebuilt after every minor change.

Closing Remarks #

The event ended with some additional React Native news:

Meetups provide a good opportunity to meet and learn from other developers in the community. I'm looking forward to attending more React Native meetups in the future. If you make it up to one of these, please look out for me and let me know how we can make React Native work better for you!

React Native Blog
Stay up-to-date with the latest React Native news and events.
React Native Blog
Stay up-to-date with the latest React Native news and events.
React Native Blog
Stay up-to-date with the latest React Native news and events.

Introducing Button, Faster Installs with Yarn, and a Public Roadmap

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:

  • Core Libraries. Adding more functionality to the most useful components and APIs.
  • Stability. Improve the underlying infrastructure to reduce bugs and improve code quality.
  • Developer Experience. Help React Native developers move faster

If you have suggestions for features that you think would be valuable on the roadmap, check out Product Pains, where you can suggest new features and discuss existing proposals.

What's new in React Native #

Version 0.37 of React Native, released today, introduces a new core component to make it really easy to add a touchable Button to any app. We're also introducing support for the new Yarn package manager, which should speed up the whole process of updating your app's dependencies.

Introducing Button #

Today we're introducing a basic <Button /> component that looks great on every platform. This addresses one of the most common pieces of feedback we get: React Native is one of the only mobile development toolkits without a button ready to use out of the box.

Simple Button on Android, iOS

<Button +Introducing Button, Faster Installs with Yarn, and a Public Roadmap
React Native Blog
Stay up-to-date with the latest React Native news and events.

Introducing Button, Faster Installs with Yarn, and a Public Roadmap

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:

  • Core Libraries. Adding more functionality to the most useful components and APIs.
  • Stability. Improve the underlying infrastructure to reduce bugs and improve code quality.
  • Developer Experience. Help React Native developers move faster

If you have suggestions for features that you think would be valuable on the roadmap, check out Canny, where you can suggest new features and discuss existing proposals.

What's new in React Native #

Version 0.37 of React Native, released today, introduces a new core component to make it really easy to add a touchable Button to any app. We're also introducing support for the new Yarn package manager, which should speed up the whole process of updating your app's dependencies.

Introducing Button #

Today we're introducing a basic <Button /> component that looks great on every platform. This addresses one of the most common pieces of feedback we get: React Native is one of the only mobile development toolkits without a button ready to use out of the box.

Simple Button on Android, iOS

<Button onPress={onPressMe} title="Press Me" accessibilityLabel="Learn more about this Simple Button" -/>

Experienced React Native developers know how to make a button: use TouchableOpacity for the default look on iOS, TouchableNativeFeedback for the ripple effect on Android, then apply a few styles. Custom buttons aren't particularly hard to build or install, but we aim to make React Native radically easy to learn. With the addition of a basic button into core, newcomers will be able to develop something awesome in their first day, rather than spending that time formatting a Button and learning about Touchable nuances.

Button is meant to work great and look native on every platform, so it won't support all the bells and whistles that custom buttons do. It is a great starting point, but is not meant to replace all your existing buttons. To learn more, check out the new Button documentation, complete with a runnable example!

Speed up react-native init using Yarn #

You can now use Yarn, the new package manager for JavaScript, to speed up react-native init significantly. To see the speedup please install yarn and upgrade your react-native-cli to 1.2.0:

$ npm install -g react-native-cli

You should now see “Using yarn” when setting up new apps:

Using yarn

In simple local testing react-native init finished in about 1 minute on a good network (vs around 3 minutes when using npm 3.10.8). Installing yarn is optional but highly recommended.

Thank you! #

We'd like to thank everyone who contributed to this release. The full release notes are now available on GitHub. With over two dozen bug fixes and new features, React Native just keeps getting better thanks to you.

React Native Blog
Stay up-to-date with the latest React Native news and events.

A Monthly Release Cadence: Releasing December and January RC

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 frequently hear feedback from the community that the release rate is hard to keep up with. Tools like Exponent had to skip every other release in order to manage the rapid change in version. So it seems clear that the bi-weekly releases did not serve the community well.

Now releasing monthly #

We're happy to announce the new monthly release cadence, and the December 2016 release, v0.40, which has been stabilizing for all last month and is ready to adopt. (Just make sure to update headers in your native modules on iOS).

Although it may vary a few days to avoid weekends or handle unforeseen issues, you can now expect a given release to be available on the first day of the month, and released on the last.

Use the current month for the best support #

The January release candidate is ready to try, and you can see what's new here.

To see what changes are coming and provide better feedback to React Native contributors, always use the current month's release candidate when possible. By the time each version is released at the end of the month, the changes it contains will have been shipped in production Facebook apps for over two weeks.

You can easily upgrade your app with the new react-native-git-upgrade command:

npm install -g react-native-git-upgrade -react-native-git-upgrade 0.41.0-rc.0

We hope this simpler approach will make it easier for the community to keep track of changes in React Native, and to adopt new versions as quickly as possible!

(Thanks go to Martin Konicek for coming up with this plan and Mike Grabowski for making it happen)

React Native Blog
Stay up-to-date with the latest React Native news and events.

Using Native Driver for Animated

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.

A Monthly Release Cadence: Releasing December and January RC

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.

San Francisco Meetup Recap

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.

Toward Better Documentation

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.

Introducing Hot Reloading

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.

React Native Blog
Stay up-to-date with the latest React Native news and events.

Using Native Driver for Animated

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.

A Monthly Release Cadence: Releasing December and January RC

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.

San Francisco Meetup Recap

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.

Toward Better Documentation

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.

Introducing Hot Reloading

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.

Profiling Android UI Performance #

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

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

Make sure that JS dev mode is OFF!

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

Profiling with Systrace #

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

Collecting a trace #

NOTE:

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

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

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

A quick breakdown of this command:

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

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

Reading the trace #

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

Example

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

ObjectObserveError

Since Object.observe was deprecated in recent browsers, you may have to open the file from the Google Chrome Tracing tool. You can do so by:

  • Opening tab in chrome chrome://tracing
  • Selecting load
  • Selecting the html file generated from the previous command.

HINT: Use the WASD keys to strafe and zoom

Enable VSync highlighting #

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

Enable VSync Highlighting

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

Find your process #

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

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

UI Thread #

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

UI Thread Example

JS Thread #

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

JS Thread Example

Native Modules Thread #

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

Native Modules Thread Example

Bonus: Render Thread #

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

Render Thread Example

Identifying a culprit #

A smooth animation should look something like the following:

Smooth Animation

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

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

Choppy Animation from JS

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

You might also see something like this:

Choppy Animation from UI

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

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

JS Issues #

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

Too much JS

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

TODO: Add more tools for profiling JS

Native UI Issues #

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

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

Too much GPU work #

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

Overloaded GPU

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

To mitigate this, you should:

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

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

Creating new views on the UI thread #

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

Creating Views

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

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

Still stuck? #

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

You can edit the content above on GitHub and send us a pull request!

Profiling Android UI Performance #

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

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

Make sure that JS dev mode is OFF!

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

Profiling with Systrace #

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

Collecting a trace #

NOTE:

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

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

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

A quick breakdown of this command:

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

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

Reading the trace #

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

Example

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

ObjectObserveError

Since Object.observe was deprecated in recent browsers, you may have to open the file from the Google Chrome Tracing tool. You can do so by:

  • Opening tab in chrome chrome://tracing
  • Selecting load
  • Selecting the html file generated from the previous command.

HINT: Use the WASD keys to strafe and zoom

Enable VSync highlighting #

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

Enable VSync Highlighting

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

Find your process #

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

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

UI Thread #

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

UI Thread Example

JS Thread #

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

JS Thread Example

Native Modules Thread #

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

Native Modules Thread Example

Bonus: Render Thread #

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

Render Thread Example

Identifying a culprit #

A smooth animation should look something like the following:

Smooth Animation

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

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

Choppy Animation from JS

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

You might also see something like this:

Choppy Animation from UI

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

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

JS Issues #

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

Too much JS

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

TODO: Add more tools for profiling JS

Native UI Issues #

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

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

Too much GPU work #

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

Overloaded GPU

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

To mitigate this, you should:

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

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

Creating new views on the UI thread #

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

Creating Views

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

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

Still stuck? #

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

You can edit the content above on GitHub and send us a pull request!

Animated #

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

The simplest workflow is to create an Animated.Value, hook it up to one or -more style attributes of an animated component, and then drive updates either -via animations, such as Animated.timing, or by hooking into gestures like -panning or scrolling via Animated.event. Animated.Value can also bind to -props other than style, and can be interpolated as well. Here is a basic -example of a container view that will fade in when it's mounted:

class FadeInView extends React.Component { - constructor(props) { - super(props); - this.state = { - fadeAnim: new Animated.Value(0), // init opacity 0 - }; - } - componentDidMount() { - Animated.timing( // Uses easing functions - this.state.fadeAnim, // The value to drive - {toValue: 1} // Configuration - ).start(); // Don't forget start! - } - render() { - return ( - <Animated.View // Special animatable View - style={{opacity: this.state.fadeAnim}}> // Binds - {this.props.children} - </Animated.View> - ); - } - }

Note that only animatable components can be animated. View, Text, and -Image are already provided, and you can create custom ones with -createAnimatedComponent. These special components do the magic of binding -the animated values to the properties, and do targeted native updates to -avoid the cost of the react render and reconciliation process on every frame. -They also handle cleanup on unmount so they are safe by default.

Animations are heavily configurable. Custom and pre-defined easing -functions, delays, durations, decay factors, spring constants, and more can -all be tweaked depending on the type of animation.

A single Animated.Value can drive any number of properties, and each -property can be run through an interpolation first. An interpolation maps -input ranges to output ranges, typically using a linear interpolation but -also supports easing functions. By default, it will extrapolate the curve -beyond the ranges given, but you can also have it clamp the output value.

For example, you may want to think about your Animated.Value as going from -0 to 1, but animate the position from 150px to 0px and the opacity from 0 to -1. This can easily be done by modifying style in the example above like so:

style={{ - opacity: this.state.fadeAnim, // Binds directly - transform: [{ - translateY: this.state.fadeAnim.interpolate({ - inputRange: [0, 1], - outputRange: [150, 0] // 0 : 150, 0.5 : 75, 1 : 0 - }), - }], - }}>

Animations can also be combined in complex ways using composition functions -such as sequence and parallel, and can also be chained together simply -by setting the toValue of one animation to be another Animated.Value.

Animated.ValueXY is handy for 2D animations, like panning, and there are -other helpful additions like setOffset and getLayout to aid with typical -interaction patterns, like drag-and-drop.

You can see more example usage in AnimationExample.js, the Gratuitous -Animation App, and Animations documentation guide.

Note that Animated is designed to be fully serializable so that animations -can be run in a high performance way, independent of the normal JavaScript -event loop. This does influence the API, so keep that in mind when it seems a -little trickier to do something compared to a fully synchronous system. -Checkout Animated.Value.addListener as a way to work around some of these -limitations, but use it sparingly since it might have performance -implications in the future.

Methods #

static decay(value, config) #

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

static timing(value, config) #

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

static spring(value, config) #

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

static add(a, b) #

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

Animated #

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 to create an +Animated.Value, hook it up to one or more style attributes of an animated +component, and then drive updates via animations using Animated.timing():

Animated.timing( // Animate value over time + this.state.fadeAnim, // The value to drive + { + toValue: 1, // Animate to final value of 1 + } +).start(); // Start the animation

Refer to the Animations guide to see +additional examples of Animated in action.

Overview #

There are two value types you can use with Animated:

Animated.Value can bind to style properties or other props, and can be +interpolated as well. A single Animated.Value can drive any number of +properties.

Configuring animations #

Animated provides three types of animation types. Each animation type +provides a particular animation curve that controls how your values animate +from their initial value to the final value:

In most cases, you will be using timing(). By default, it uses a symmetric +easeInOut curve that conveys the gradual acceleration of an object to full +speed and concludes by gradually decelerating to a stop.

Working with animations #

Animations are started by calling start() on your animation. start() +takes a completion callback that will be called when the animation is done. +If the animation finished running normally, the completion callback will be +invoked with {finished: true}. If the animation is done because stop() +was called on it before it could finish (e.g. because it was interrupted by a +gesture or another animation), then it will receive {finished: false}.

Using the native driver #

By using the native driver, we send everything about the animation to native +before starting the animation, allowing native code to perform the animation +on the UI thread without having to go through the bridge on every frame. +Once the animation has started, the JS thread can be blocked without +affecting the animation.

You can use the native driver by specifying useNativeDriver: true in your +animation configuration. See the +Animations guide to learn +more.

Animatable components #

Only animatable components can be animated. These special components do the +magic of binding the animated values to the properties, and do targeted +native updates to avoid the cost of the react render and reconciliation +process on every frame. They also handle cleanup on unmount so they are safe +by default.

Animated exports the following animatable components using the above +wrapper:

  • Animated.Image
  • Animated.ScrollView
  • Animated.Text
  • Animated.View

Composing animations #

Animations can also be combined in complex ways using composition functions:

Animations can also be chained together simply by setting the toValue of +one animation to be another Animated.Value. See +Tracking dynamic values in +the Animations guide.

By default, if one animation is stopped or interrupted, then all other +animations in the group are also stopped.

Combining animated values #

You can combine two animated values via addition, multiplication, division, +or modulo to make a new animated value:

Interpolation #

The interpolate() function allows input ranges to map to different output +ranges. By default, it will extrapolate the curve beyond the ranges given, +but you can also have it clamp the output value. It uses lineal interpolation +by default but also supports easing functions.

Read more about interpolation in the +Animation guide.

Handling gestures and other events #

Gestures, like panning or scrolling, and other events can map directly to +animated values using Animated.event(). This is done with a structured map +syntax so that values can be extracted from complex event objects. The first +level is an array to allow mapping across multiple args, and that array +contains nested objects.

For example, when working with horizontal scrolling gestures, you would do +the following in order to map event.nativeEvent.contentOffset.x to +scrollX (an Animated.Value):

onScroll={Animated.event( + // scrollX = e.nativeEvent.contentOffset.x + [{ nativeEvent: { + contentOffset: { + x: scrollX + } + } + }] + )}

Methods #

static decay(value, config) #

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

Config is an object that may have the following options:

  • velocity: Initial velocity. Required.
  • deceleration: Rate of decay. Default 0.997.
  • useNativeDriver: Uses the native driver when true. Default false.

static timing(value, config) #

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

Config is an object that may have the following options:

  • duration: Length of animation (milliseconds). Default 500.
  • easing: Easing function to define curve. +Default is Easing.inOut(Easing.ease).
  • delay: Start the animation after delay (milliseconds). Default 0.
  • useNativeDriver: Uses the native driver when true. Default false.

static spring(value, config) #

Spring animation based on Rebound and +Origami. 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:

  • friction: Controls "bounciness"/overshoot. Default 7.
  • tension: Controls speed. Default 40.
  • useNativeDriver: Uses the native driver when true. Default false.

static add(a, b) #

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

static divide(a, b) #

Creates a new Animated value composed by dividing the first Animated value by the second Animated value.

static multiply(a, b) #

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

static modulo(a, modulus) #

Creates a new Animated value that is the (non-negative) modulo of the @@ -74,8 +82,8 @@ before starting the next. If the current running animation is stopped, no following animations will be started.

static parallel(animations, config?) #

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

static stagger(time, animations) #

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

static event(argMapping, config?) #

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

onScroll={Animated.event( +sequence with successive delays. Nice for doing trailing effects.

static event(argMapping, config?) #

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

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

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

static createAnimatedComponent(Component) #

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

Properties #

Value: AnimatedValue #

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

ValueXY: AnimatedValueXY #

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

Interpolation: AnimatedInterpolation #

exported to use the Interpolation type in flow

class AnimatedValue #

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

    Config is an object that may have the following options:

    • listener: Optional async listener.
    • useNativeDriver: Uses the native driver when true. Default false.

static createAnimatedComponent(Component) #

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

Properties #

Value: AnimatedValue #

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

See also AnimatedValue.

ValueXY: AnimatedValueXY #

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

See also AnimatedValueXY.

Interpolation: AnimatedInterpolation #

exported to use the Interpolation type in flow

See also AnimatedInterpolation.

class AnimatedValue #

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

    Methods #

    constructor(value) #

    setValue(value) #

    Directly set the value. This will stop any animations running on the value @@ -100,7 +108,7 @@ state to match the animation position with layout.

    animate(animation, callback) #

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

    stopTracking(0) #

    Typically only used internally.

    track(tracking) #

    Typically only used internally.

class AnimatedValueXY #

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

    class DraggableView extends React.Component { +Animated.Values under the hood.

    Example #

    class DraggableView extends React.Component { constructor(props) { super(props); this.state = { @@ -351,7 +359,7 @@ exports.examples : 10, alignItems: 'center', }, -});

Animations #

Fluid, meaningful animations are essential to the mobile user experience. Like -everything in React Native, Animation APIs for React Native are currently under -development, but have started to coalesce around two complementary systems: -LayoutAnimation for animated global layout transactions, and Animated for -more granular and interactive control of specific values.

Animated #

The Animated library is designed to make it very easy to concisely express a -wide variety of interesting animation and interaction patterns in a very -performant way. Animated focuses on declarative relationships between inputs -and outputs, with configurable transforms in between, and simple start/stop -methods to control time-based animation execution. For example, a complete -component with a simple spring bounce on mount looks like this:

class Playground extends React.Component { +Animations

Animations #

Animations are very important to create a great user experience. +Stationary objects must overcome inertia as they start moving. +Objects in motion have momentum and rarely come to a stop immediately. +Animations allow you to convey physically believable motion in your interface.

React Native provides two complementary animation systems: +Animated for granular and interactive control of specific values, and +LayoutAnimation for animated global layout transactions.

Animated API #

The Animated API is designed to make it very easy to concisely express a wide variety of interesting animation and interaction patterns in a very performant way. +Animated focuses on declarative relationships between inputs and outputs, with configurable transforms in between, and simple start/stop methods to control time-based animation execution.

Animated exports four animatable component types: View, Text, Image, and ScrollView, but you can also create your own using Animated.createAnimatedComponent().

For example, a container view that fades in when it is mounted may look like this:

// FadeInView.js +import React, { Component } from 'react'; +import { + Animated, +} from 'react-native'; + +class FadeInView extends Component { constructor(props) { super(props); this.state = { - bounceValue: new Animated.Value(0), - }; - } - render() { - return ( - <Animated.Image // Base: Image, Text, View - source={{uri: 'http://i.imgur.com/XMKOH81.jpg'}} - style={{ - flex: 1, - transform: [ // `transform` is an ordered array - {scale: this.state.bounceValue}, // Map `bounceValue` to `scale` - ] - }} - /> - ); + fadeAnim: new Animated.Value(0), // Initial value for opacity: 0 + }; } componentDidMount() { - this.state.bounceValue.setValue(1.5); // Start large - Animated.spring( // Base: spring, decay, timing - this.state.bounceValue, // Animate `bounceValue` + Animated.timing( // Animate over time + this.state.fadeAnim, // The animated value to drive { - toValue: 0.8, // Animate to smaller size - friction: 1, // Bouncier spring + toValue: 1, // Animate to opacity: 1, or fully opaque } - ).start(); // Start the animation + ).start(); // Starts the animation } -}

bounceValue is initialized as part of state in the constructor, and mapped -to the scale transform on the image. Behind the scenes, the numeric value is -extracted and used to set scale. When the component mounts, the scale is set to -1.5 and then a spring animation is started on bounceValue which will update -all of its dependent mappings on each frame as the spring animates (in this -case, just the scale). This is done in an optimized way that is faster than -calling setState and re-rendering. Because the entire configuration is -declarative, we will be able to implement further optimizations that serialize -the configuration and runs the animation on a high-priority thread.

Core API #

Most everything you need hangs directly off the Animated module. This -includes two value types, Value for single values and ValueXY for vectors, -three animation types, spring, decay, and timing, and three component -types, View, Text, and Image. You can make any other component animated with -Animated.createAnimatedComponent.

The three animation types can be used to create almost any animation curve you -want because each can be customized:

  • spring: Simple single-spring physics model that matches Origami.
    • friction: Controls "bounciness"/overshoot. Default 7.
    • tension: Controls speed. Default 40.
  • decay: Starts with an initial velocity and gradually slows to a stop.
    • velocity: Initial velocity. Required.
    • deceleration: Rate of decay. Default 0.997.
  • timing: Maps time range to easing value.
    • duration: Length of animation (milliseconds). Default 500.
    • easing: Easing function to define curve. See Easing module for several -predefined functions. iOS default is Easing.inOut(Easing.ease).
    • delay: Start the animation after delay (milliseconds). Default 0.

Animations are started by calling start. start takes a completion callback -that will be called when the animation is done. If the animation is done -because it finished running normally, the completion callback will be invoked -with {finished: true}, but if the animation is done because stop was called -on it before it could finish (e.g. because it was interrupted by a gesture or -another animation), then it will receive {finished: false}.

Composing Animations #

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

Animated.sequence([ // spring to start and twirl after decay finishes + render() { + return ( + <Animated.View // Special animatable View + style={{ + ...this.props.style, + opacity: this.state.fadeAnim, // Bind opacity to animated value + }} + > + {this.props.children} + </Animated.View> + ); + } +} + +module.exports = FadeInView;

You can then use your FadeInView in place of a View in your components, like so:

render() { + return ( + <FadeInView style={{width: 250, height: 50, backgroundColor: 'powderblue'}}> + <Text style={{fontSize: 28, textAlign: 'center', margin: 10}}>Fading in</Text> + </FadeInView> + ) +}

FadeInView

Let's break down what's happening here. +In the FadeInView constructor, a new Animated.Value called fadeAnim is initialized as part of state. +The opacity property on the View is mapped to this animated value. +Behind the scenes, the numeric value is extracted and used to set opacity.

When the component mounts, the opacity is set to 0. +Then, an easing animation is started on the fadeAnim animated value, +which will update all of its dependent mappings (in this case, just the opacity) on each frame as the value animates to the final value of 1.

This is done in an optimized way that is faster than calling setState and re-rendering.
Because the entire configuration is declarative, we will be able to implement further optimizations that serialize the configuration and runs the animation on a high-priority thread.

Configuring animations #

Animations are heavily configurable. Custom and predefined easing functions, delays, durations, decay factors, spring constants, and more can all be tweaked depending on the type of animation.

Animated provides several animation types, the most commonly used one being Animated.timing(). +It supports animating a value over time using one of various predefined easing functions, or you can use your own. +Easing functions are typically used in animation to convey gradual acceleration and deceleration of objects.

By default, timing will use a easeInOut curve that conveys gradual acceleration to full speed and concludes by gradually decelerating to a stop. +You can specify a different easing function by passing a easing parameter. +Custom duration or even a delay before the animation starts is also supported.

For example, if we want to create a 2-second long animation of an object that slightly backs up before moving to its final position:

Animated.timing( + this.state.xPosition, + { + toValue: 100, + easing: Easing.back, + duration: 2000, + } +).start();

Take a look at the Configuring animations section of the Animated API reference to learn more about all the config parameters supported by the built-in animations.

Composing animations #

Animations can be combined and played in sequence or in parallel. +Sequential animations can play immediately after the previous animation has finished, +or they can start after a specified delay. +The Animated API provides several methods, such as sequence() and delay(), +each of which simply take an array of animations to execute and automatically calls start()/stop() as needed.

For example, the following animation coasts to a stop, then it springs back while twirling in parallel:

Animated.sequence([ // decay, then spring to start and twirl Animated.decay(position, { // coast to a stop velocity: {x: gestureState.vx, y: gestureState.vy}, // velocity from gesture release deceleration: 0.997, @@ -71,78 +78,117 @@ automatically calls start/stop as appropriate. For example:

: 360, }), ]), -]).start(); // start the sequence group

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

Interpolation #

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

value.interpolate({ +]).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.

Combining animated values #

You can combine two animated values via addition, multiplication, division, or modulo to make a new animated value.

There are some cases where an animated value needs to invert another animated value for calculation. +An example is inverting a scale (2x --> 0.5x):

const a = Animated.Value(1); +const b = Animated.divide(1, a); + +Animated.spring(a, { + toValue: 2, +}).start();

Interpolation #

Each property can be run through an interpolation first. +An interpolation maps input ranges to output ranges, +typically using a linear interpolation but also supports easing functions. +By default, it will extrapolate the curve beyond the ranges given, but you can also have it clamp the output value.

A simple mapping to convert a 0-1 range to a 0-100 range would be:

value.interpolate({ inputRange: [0, 1], outputRange: [0, 100], -});

interpolate supports multiple range segments as well, which is handy for -defining dead zones and other handy tricks. For example, to get an negation -relationship at -300 that goes to 0 at -100, then back up to 1 at 0, and then -back down to zero at 100 followed by a dead-zone that remains at 0 for -everything beyond that, you could do:

value.interpolate({ +});

For example, you may want to think about your Animated.Value as going from 0 to 1, +but animate the position from 150px to 0px and the opacity from 0 to 1. +This can easily be done by modifying style from the example above like so:

style={{ + opacity: this.state.fadeAnim, // Binds directly + transform: [{ + translateY: this.state.fadeAnim.interpolate({ + inputRange: [0, 1], + outputRange: [150, 0] // 0 : 150, 0.5 : 75, 1 : 0 + }), + }], + }}

interpolate() supports multiple range segments as well, which is handy for defining dead zones and other handy tricks. +For example, to get an negation relationship at -300 that goes to 0 at -100, then back up to 1 at 0, and then back down to zero at 100 followed by a dead-zone that remains at 0 for everything beyond that, you could do:

value.interpolate({ inputRange: [-300, -100, 0, 100, 101], outputRange: [300, 0, 1, 0, 0], -});

Which would map like so:

InputOutput
-400450
-300300
-200150
-1000
-500.5
01
500.5
1000
1010
2000

interpolate also supports mapping to strings, allowing you to animate colors as well as values with units. For example, if you wanted to animate a rotation you could do:

value.interpolate({ +});

Which would map like so:

Input | Output +------|------- + -400| 450 + -300| 300 + -200| 150 + -100| 0 + -50| 0.5 + 0| 1 + 50| 0.5 + 100| 0 + 101| 0 + 200| 0

interpolate() also supports mapping to strings, allowing you to animate colors as well as values with units. For example, if you wanted to animate a rotation you could do:

value.interpolate({ inputRange: [0, 360], outputRange: ['0deg', '360deg'] -})

interpolation also supports arbitrary easing functions, many of which are -already implemented in the -Easing -class including quadratic, exponential, and bezier curves as well as functions -like step and bounce. interpolation also has configurable behavior for -extrapolating the outputRange. You can set the extrapolation by setting the extrapolate, -extrapolateLeft or extrapolateRight options. The default value is -extend but you can use clamp to prevent the output value from exceeding -outputRange.

Tracking Dynamic Values #

Animated values can also track other values. Just set the toValue of an -animation to another animated value instead of a plain number, for example with -spring physics for an interaction like "Chat Heads", or via timing with -duration: 0 for rigid/instant tracking. They can also be composed with -interpolations:

Animated.spring(follower, {toValue: leader}).start(); +})

interpolate() also supports arbitrary easing functions, many of which are already implemented in the +Easing module. +interpolate() also has configurable behavior for extrapolating the outputRange. +You can set the extrapolation by setting the extrapolate, extrapolateLeft, or extrapolateRight options. +The default value is extend but you can use clamp to prevent the output value from exceeding outputRange.

Tracking dynamic values #

Animated values can also track other values. +Just set the toValue of an animation to another animated value instead of a plain number. +For example, a "Chat Heads" animation like the one used by Messenger on Android could be implemented with a spring() pinned on another animated value, or with timing() and a duration of 0 for rigid tracking. +They can also be composed with interpolations:

Animated.spring(follower, {toValue: leader}).start(); Animated.timing(opacity, { toValue: pan.x.interpolate({ inputRange: [0, 300], outputRange: [1, 0], }), -}).start();

ValueXY is a handy way to deal with 2D interactions, such as panning/dragging. -It is a simple wrapper that basically just contains two Animated.Value -instances and some helper functions that call through to them, making ValueXY -a drop-in replacement for Value in many cases. For example, in the code -snippet above, leader and follower could both be of type ValueXY and the x -and y values will both track as you would expect.

Input Events #

Animated.event is the input side of the Animated API, allowing gestures and -other events to map directly to animated values. This is done with a structured -map syntax so that values can be extracted from complex event objects. The -first level is an array to allow mapping across multiple args, and that array -contains nested objects. In the example, you can see that scrollX maps to -event.nativeEvent.contentOffset.x (event is normally the first arg to the -handler), and pan.x and pan.y map to gestureState.dx and gestureState.dy, -respectively (gestureState is the second arg passed to the PanResponder handler).

onScroll={Animated.event( - // scrollX = e.nativeEvent.contentOffset.x - [{nativeEvent: {contentOffset: {x: scrollX}}}] -)} -onPanResponderMove={Animated.event([ - null, // ignore the native event +}).start();

The leader and follower animated values would be implemented using Animated.ValueXY(). +ValueXY is a handy way to deal with 2D interactions, such as panning or dragging. +It is a simple wrapper that basically contains two Animated.Value instances and some helper functions that call through to them, +making ValueXY a drop-in replacement for Value in many cases. +It allows us to track both x and y values in the example above.

Tracking gestures #

Gestures, like panning or scrolling, and other events can map directly to animated values using Animated.event. +This is done with a structured map syntax so that values can be extracted from complex event objects. +The first level is an array to allow mapping across multiple args, and that array contains nested objects.

For example, when working with horizontal scrolling gestures, +you would do the following in order to map event.nativeEvent.contentOffset.x to scrollX (an Animated.Value):

onScroll={Animated.event( + // scrollX = e.nativeEvent.contentOffset.x + [{ nativeEvent: { + contentOffset: { + x: scrollX + } + } + }] + )}

When using PanResponder, you could use the following code to extract the x and y positions from gestureState.dx and gestureState.dy. +We use a null in the first position of the array, as we are only interested in the second argument passed to the PanResponder handler, +which is the gestureState.

onPanResponderMove={Animated.event( + [null, // ignore the native event // extract dx and dy from gestureState // like 'pan.x = gestureState.dx, pan.y = gestureState.dy' {dx: pan.x, dy: pan.y} -]);

Responding to the Current Animation Value #

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

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

Future Work #

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

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

LayoutAnimation #

LayoutAnimation allows you to globally configure create and update +])}

Responding to the current animation value #

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

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

Animated is designed to be fully serializable so that animations can be run in a high performance way, independent of the normal JavaScript event loop. +This does influence the API, so keep that in mind when it seems a little trickier to do something compared to a fully synchronous system. +Check out Animated.Value.addListener as a way to work around some of these limitations, +but use it sparingly since it might have performance implications in the future.

Using the native driver #

The Animated API is designed to be serializable. +By using the native driver, +we send everything about the animation to native before starting the animation, +allowing native code to perform the animation on the UI thread without having to go through the bridge on every frame. +Once the animation has started, the JS thread can be blocked without affecting the animation.

Using the native driver for normal animations is quite simple. +Just add useNativeDriver: true to the animation config when starting it.

Animated.timing(this.state.animatedValue, { + toValue: 1, + duration: 500, + useNativeDriver: true, // <-- Add this +}).start();

Animated values are only compatible with one driver so if you use native driver when starting an animation on a value, +make sure every animation on that value also uses the native driver.

The native driver also works with Animated.event. +This is specially useful for animations that follow the scroll position as without the native driver, +the animation will always run a frame behind the gesture due to the async nature of React Native.

<Animated.ScrollView // <-- Use the Animated ScrollView wrapper + scrollEventThrottle={1} // <-- Use 1 here to make sure no events are ever missed + onScroll={Animated.event( + [{ nativeEvent: { contentOffset: { y: this.state.animatedValue } } }], + { useNativeDriver: true } // <-- Add this + )} +> + {content} +</Animated.ScrollView>

You can see the native driver in action by running the UIExplorer sample app, +then loading the Native Animated Example. +You can also take a look at the source code to learn how these examples were produced.

Caveats #

Not everything you can do with Animated is currently supported by the native driver. +The main limitation is that you can only animate non-layout properties: +things like transform, opacity and backgroundColor will work, but flexbox and position properties will not. +When using Animated.event, it will only work with direct events and not bubbling events. +This means it does not work with PanResponder but does work with things like ScrollView#onScroll.

Additional examples #

The UIExplorer sample app has various examples of Animated in use:

LayoutAnimation API #

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

Note that in order to get this to work on Android} }

Run this example

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

requestAnimationFrame #

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

Additional notes #

requestAnimationFrame #

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

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

react-tween-state is a -minimal library that does exactly what its name suggests: it tweens a -value in a component's state, starting at a from value and ending at -a to value. This means that it generates the values in between those -two values, and it sets the state on every requestAnimationFrame with -the intermediary value.

Tweening definition from Wikipedia

"... tweening is the process of generating intermediate frames between two -images to give the appearance that the first image evolves smoothly -into the second image. [Tweens] are the drawings between the key -frames which help to create the illusion of motion."

The most obvious way to animate from one value to another is linearly: -you subtract the end value from the start value and divide the result by -the number of frames over which the animation occurs, and then add that -value to the current value on each frame until the end value is reached. -Linear easing often looks awkward and unnatural, so react-tween-state -provides a selection of popular easing functions -that can be applied to make your animations more pleasing.

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

import tweenState from 'react-tween-state'; -import reactMixin from 'react-mixin'; // https://github.com/brigand/react-mixin - -class App extends React.Component { - constructor(props) { - super(props); - this.state = { opacity: 1 }; - this._animateOpacity = this._animateOpacity.bind(this); - } - - _animateOpacity() { - this.tweenState('opacity', { - easing: tweenState.easingTypes.easeOutQuint, - duration: 1000, - endValue: this.state.opacity === 0.2 ? 1 : 0.2, - }); - } - - render() { - return ( - <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}> - <TouchableWithoutFeedback onPress={this._animateOpacity}> - <View ref={component => this._box = component} - style={{width: 200, height: 200, backgroundColor: 'red', - opacity: this.getTweeningValue('opacity')}} /> - </TouchableWithoutFeedback> - </View> - ) - } -} - -reactMixin.onClass(App, tweenState.Mixin);

Run this example

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

Rebound (Not recommended - use Animated instead) #

Rebound.js is a JavaScript port of -Rebound for Android. It is -similar in concept to react-tween-state: you have an initial value and -set an end value, then Rebound generates intermediate values that you can -use for your animation. Rebound is modeled after spring physics; we -don't provide a duration when animating with springs, it is -calculated for us depending on the spring tension, friction, current -value and end value. Rebound is used -internally -by React Native on Navigator and WarningBox.

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

import rebound from 'rebound'; - -class App extends React.Component { - constructor(props) { - super(props); - this._onPressIn = this._onPressIn.bind(this); - this._onPressOut = this._onPressOut.bind(this); - } - // First we initialize the spring and add a listener, which calls - // setState whenever it updates - componentWillMount() { - // Initialize the spring that will drive animations - this.springSystem = new rebound.SpringSystem(); - this._scrollSpring = this.springSystem.createSpring(); - var springConfig = this._scrollSpring.getSpringConfig(); - springConfig.tension = 230; - springConfig.friction = 10; - - this._scrollSpring.addListener({ - onSpringUpdate: () => { - this.setState({scale: this._scrollSpring.getCurrentValue()}); - }, - }); - - // Initialize the spring value at 1 - this._scrollSpring.setCurrentValue(1); - } - - _onPressIn() { - this._scrollSpring.setEndValue(0.5); - } - - _onPressOut() { - this._scrollSpring.setEndValue(1); - } - - render() { - var imageStyle = { - width: 250, - height: 200, - transform: [{scaleX: this.state.scale}, {scaleY: this.state.scale}], - }; - - var imageUri = "img/ReboundExample.png"; - - return ( - <View style={styles.container}> - <TouchableWithoutFeedback onPressIn={this._onPressIn} - onPressOut={this._onPressOut}> - <Image source={{uri: imageUri}} style={imageStyle} /> - </TouchableWithoutFeedback> - </View> - ); - } -}

Run this example

You can also clamp the spring values so that they don't overshoot and -oscillate around the end value. In the above example, we would add -this._scrollSpring.setOvershootClampingEnabled(true) to change this. -See the below gif for an example of where in your interface you might -use this.

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

A sidenote about setNativeProps #

As mentioned in the Direction Manipulation section, +manage frame updates for you.

setNativeProps #

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

Navigator Scene Transitions #

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

import { Dimensions } from 'react-native'; -var SCREEN_WIDTH = Dimensions.get('window').width; -var BaseConfig = Navigator.SceneConfigs.FloatFromRight; - -var CustomLeftToRightGesture = Object.assign({}, BaseConfig.gestures.pop, { - // Make it snap back really quickly after canceling pop - snapVelocity: 8, - - // Make it so we can drag anywhere on the screen - edgeHitWidth: SCREEN_WIDTH, -}); - -var CustomSceneConfig = Object.assign({}, BaseConfig, { - // A very tightly wound spring will make this transition fast - springTension: 100, - springFriction: 1, - - // Use our custom gesture defined above - gestures: { - pop: CustomLeftToRightGesture, - } -});

Run this example

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

You can edit the content above on GitHub and send us a pull request!

Colors #

The following formats are supported:

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

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

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

You can edit the content above on GitHub and send us a pull request!

Colors #

The following formats are supported:

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

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

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

You can edit the content above on GitHub and send us a pull request!

Easing #

This class implements common easing functions. The math is pretty obscure, -but this cool website has nice visual illustrations of what they represent: -http://xaedes.de/dev/transitions/

Methods #

static step0(n) #

static step1(n) #

static linear(t) #

static ease(t) #

static quad(t) #

static cubic(t) #

static poly(n) #

static sin(t) #

static circle(t) #

static exp(t) #

static elastic(bounciness) #

A simple elastic interaction, similar to a spring. Default bounciness -is 1, which overshoots a little bit once. 0 bounciness doesn't overshoot -at all, and bounciness of N > 1 will overshoot about N times.

Wolfram Plots:

http://tiny.cc/elastic_b_1 (default bounciness = 1) - http://tiny.cc/elastic_b_3 (bounciness = 3)

static back(s) #

static bounce(t) #

static bezier(x1, y1, x2, y2) #

static in(easing) #

static out(easing) #

Runs an easing function backwards.

static inOut(easing) #

Makes any easing function symmetrical.

You can edit the content above on GitHub and send us a pull request!

Easing #

The Easing module implements common easing functions. This module is used +by Animate.timing() to convey physically +believable motion in animations.

You can find a visualization of some common easing functions at +http://easings.net/

Predefined animations #

The Easing module provides several predefined animations through the +following methods:

  • back provides a simple animation where the +object goes slightly back before moving forward
  • bounce provides a bouncing animation
  • ease provides a simple inertial animation
  • elastic provides a simple spring interaction

Standard functions #

Three standard easing functions are provided:

The poly function can be used to implement +quartic, quintic, and other higher power functions.

Additional functions #

Additional mathematical functions are provided by the following methods:

  • bezier provides a cubic bezier curve
  • circle provides a circular function
  • sin provides a sinusoidal function
  • exp provides an exponential function

The following helpers are used to modify other easing functions.

  • in runs an easing function forwards
  • inOut makes any easing function symmetrical
  • out runs an easing function backwards

Methods #

static step0(n) #

A stepping function, returns 1 for any positive value of n.

static step1(n) #

A stepping function, returns 1 if n is greater than or equal to 1.

static linear(t) #

A linear function, f(t) = t. Position correlates to elapsed time one to +one.

http://cubic-bezier.com/#0,0,1,1

static ease(t) #

A simple inertial interaction, similar to an object slowly accelerating to +speed.

http://cubic-bezier.com/#.42,0,1,1

static quad(t) #

A quadratic function, f(t) = t * t. Position equals the square of elapsed +time.

http://easings.net/#easeInQuad

static cubic(t) #

A cubic function, f(t) = t * t * t. Position equals the cube of elapsed +time.

http://easings.net/#easeInCubic

static poly(n) #

A power function. Position is equal to the Nth power of elapsed time.

n = 4: http://easings.net/#easeInQuart +n = 5: http://easings.net/#easeInQuint

static sin(t) #

A sinusoidal function.

http://easings.net/#easeInSine

static circle(t) #

A circular function.

http://easings.net/#easeInCirc

static exp(t) #

An exponential function.

http://easings.net/#easeInExpo

static elastic(bounciness) #

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.

http://easings.net/#easeInElastic

Wolfram Plots:

static back(s) #

Use with Animated.parallel() to create a simple effect where the object +animates back slightly as the animation starts.

Wolfram Plot:

static bounce(t) #

Provides a simple bouncing effect.

http://easings.net/#easeInBounce

static bezier(x1, y1, x2, y2) #

Provides a cubic bezier curve, equivalent to CSS Transitions' +transition-timing-function.

A useful tool to visualize cubic bezier curves can be found at +http://cubic-bezier.com/

static in(easing) #

Runs an easing function forwards.

static out(easing) #

Runs an easing function backwards.

static inOut(easing) #

Makes any easing function symmetrical. The easing function will run +forwards for half of the duration, then backwards for the rest of the +duration.

You can edit the content above on GitHub and send us a pull request!

Gesture Responder System #

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.

Best Practices #

To make your app feel great, every action should have the following attributes:

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

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

TouchableHighlight and Touchable* #

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

Responder Lifecycle #

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

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

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

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

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

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

evt is a synthetic touch event with the following form:

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

Capture ShouldSet Handlers #

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

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

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

PanResponder #

For higher-level gesture interpretation, check out PanResponder.

You can edit the content above on GitHub and send us a pull request!

Gesture Responder System #

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.

Best Practices #

To make your app feel great, every action should have the following attributes:

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

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

TouchableHighlight and Touchable* #

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

Responder Lifecycle #

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

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

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

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

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

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

evt is a synthetic touch event with the following form:

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

Capture ShouldSet Handlers #

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

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

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

PanResponder #

For higher-level gesture interpretation, check out PanResponder.

You can edit the content above on GitHub and send us a pull request!

-

You can edit the content above on GitHub and send us a pull request!

ImagePickerIOS #

Methods #

static canRecordVideos(callback) #

static canUseCamera(callback) #

static openCameraDialog(config, successCallback, cancelCallback) #

static openSelectDialog(config, successCallback, cancelCallback) #

You can edit the content above on GitHub and send us a pull request!

ImagePickerIOS #

Methods #

static canRecordVideos(callback) #

static canUseCamera(callback) #

static openCameraDialog(config, successCallback, cancelCallback) #

static openSelectDialog(config, successCallback, cancelCallback) #

You can edit the content above on GitHub and send us a pull request!

JavaScript Environment #

JavaScript Runtime #

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

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

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

JavaScript Syntax Transformers #

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

As of version 0.5.0, React Native ships with the Babel JavaScript compiler. Check Babel documentation on its supported transformations for more details.

Here's a full list of React Native's enabled transformations.

ES5

  • Reserved Words: promise.catch(function() { });

ES6

ES7

Specific

  • JSX: <View style={{color: 'red'}} />
  • Flow: function foo(x: ?number): string {}

Polyfills #

Many standards functions are also available on all the supported JavaScript runtimes.

Browser

ES6

ES7

Specific

  • __DEV__

You can edit the content above on GitHub and send us a pull request!

JavaScript Environment #

JavaScript Runtime #

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

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

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

JavaScript Syntax Transformers #

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

As of version 0.5.0, React Native ships with the Babel JavaScript compiler. Check Babel documentation on its supported transformations for more details.

Here's a full list of React Native's enabled transformations.

ES5

  • Reserved Words: promise.catch(function() { });

ES6

ES7

Specific

  • JSX: <View style={{color: 'red'}} />
  • Flow: function foo(x: ?number): string {}

Polyfills #

Many standards functions are also available on all the supported JavaScript runtimes.

Browser

ES6

ES7

Specific

  • __DEV__

You can edit the content above on GitHub and send us a pull request!

More Resources #

If you just read through this website, you should be able to build a pretty cool React Native app. But React Native isn't just a product made by one company - it's a community of thousands of developers. So if you're interested in React Native, here's some related stuff you might want to check out.

Popular Libraries #

If you're using React Native, you probably already know about React. So I feel a bit silly mentioning this. But if you haven't, check out React - it's the best way to build a modern website.

One common question is how to handle the "state" of your React Native application. The most popular library for this is Redux. Don't be afraid of how often Redux uses the word "reducer" - it's a pretty simple library, and there's also a nice series of videos explaining it.

If you're looking for a library that does a specific thing, check out Awesome React Native, a curated list of components that also has demos, articles, and other stuff.

Example Apps #

There are a lot of example apps at the React Native Playground. You can see the code running on a real device, which is a neat feature.

The folks who built the app for Facebook's F8 conference in 2016 also open-sourced the code and wrote up a detailed series of tutorials. This is useful if you want a more in-depth example that's more realistic than most sample apps out there.

Development Tools #

Nuclide is the IDE that Facebook uses internally for React Native development. The killer feature of Nuclide is its debugging ability. It also has great inline Flow support.

Ignite is a starter kit that uses Redux and a few different common UI libraries. It has a CLI to generate apps, components, and containers. If you like all of the individual tech choices, Ignite could be perfect for you.

CodePush is a service from Microsoft that makes it easy to deploy live updates to your React Native app. If you don't like going through the app store process to deploy little tweaks, and you also don't like setting up your own backend, give CodePush a try.

Exponent is a development environment plus application that focuses on letting you build React Native apps in the Exponent development environment, without ever touching Xcode or Android Studio. If you wish React Native was even more JavaScripty and webby, check out Exponent.

Deco is an all-in-one development environment specifically designed for React Native. It can automatically set up a new project, search for open source components, and insert them. You can also tweak your app graphically in real time. Check it out if you use macOS.

Where React Native People Hang Out #

The React Native Community Facebook group has thousands of developers, and it's pretty active. Come there to show off your project, or ask how other people solved similar problems.

Reactiflux is a Discord chat where a lot of React-related discussion happens, including React Native. Discord is just like Slack except it works better for open source projects with a zillion contributors. Check out the #react-native channel.

The React Twitter account covers both React and React Native. Follow the React Native Twitter account and blog to find out what's happening in the world of React Native.

There are a lot of React Native Meetups that happen around the world. Often there is React Native content in React meetups as well.

Sometimes we have React conferences. We posted the videos from React.js Conf 2016, and we'll probably have more conferences in the future, too. Stay tuned.

You can edit the content above on GitHub and send us a pull request!

More Resources #

If you just read through this website, you should be able to build a pretty cool React Native app. But React Native isn't just a product made by one company - it's a community of thousands of developers. So if you're interested in React Native, here's some related stuff you might want to check out.

Popular Libraries #

If you're using React Native, you probably already know about React. So I feel a bit silly mentioning this. But if you haven't, check out React - it's the best way to build a modern website.

One common question is how to handle the "state" of your React Native application. The most popular library for this is Redux. Don't be afraid of how often Redux uses the word "reducer" - it's a pretty simple library, and there's also a nice series of videos explaining it.

If you're looking for a library that does a specific thing, check out Awesome React Native, a curated list of components that also has demos, articles, and other stuff.

Example Apps #

There are a lot of example apps at the React Native Playground. You can see the code running on a real device, which is a neat feature.

The folks who built the app for Facebook's F8 conference in 2016 also open-sourced the code and wrote up a detailed series of tutorials. This is useful if you want a more in-depth example that's more realistic than most sample apps out there.

Development Tools #

Nuclide is the IDE that Facebook uses internally for React Native development. The killer feature of Nuclide is its debugging ability. It also has great inline Flow support.

Ignite is a starter kit that uses Redux and a few different common UI libraries. It has a CLI to generate apps, components, and containers. If you like all of the individual tech choices, Ignite could be perfect for you.

CodePush is a service from Microsoft that makes it easy to deploy live updates to your React Native app. If you don't like going through the app store process to deploy little tweaks, and you also don't like setting up your own backend, give CodePush a try.

Exponent is a development environment plus application that focuses on letting you build React Native apps in the Exponent development environment, without ever touching Xcode or Android Studio. If you wish React Native was even more JavaScripty and webby, check out Exponent.

Deco is an all-in-one development environment specifically designed for React Native. It can automatically set up a new project, search for open source components, and insert them. You can also tweak your app graphically in real time. Check it out if you use macOS.

Where React Native People Hang Out #

The React Native Community Facebook group has thousands of developers, and it's pretty active. Come there to show off your project, or ask how other people solved similar problems.

Reactiflux is a Discord chat where a lot of React-related discussion happens, including React Native. Discord is just like Slack except it works better for open source projects with a zillion contributors. Check out the #react-native channel.

The React Twitter account covers both React and React Native. Follow the React Native Twitter account and blog to find out what's happening in the world of React Native.

There are a lot of React Native Meetups that happen around the world. Often there is React Native content in React meetups as well.

Sometimes we have React conferences. We posted the videos from React.js Conf 2016, and we'll probably have more conferences in the future, too. Stay tuned.

You can edit the content above on GitHub and send us a pull request!

-
← PrevNext →

You can edit the content above on GitHub and send us a pull request!

Running On Simulator #

Starting the simulator #

Once you have your React Native project initialized, you can run react-native run-ios inside the newly created project directory. If everything is set up correctly, you should see your new app running in the iOS Simulator shortly.

Specifying a device #

You can specify the device the simulator should run with the --simulator flag, followed by the device name as a string. The default is "iPhone 6". If you wish to run your app on an iPhone 4s, just run react-native run-ios --simulator="iPhone 4s".

The device names correspond to the list of devices available in Xcode. You can check your available devices by running xcrun simctl list devices from the console.

You can edit the content above on GitHub and send us a pull request!

Running On Simulator #

Starting the simulator #

Once you have your React Native project initialized, you can run react-native run-ios inside the newly created project directory. If everything is set up correctly, you should see your new app running in the iOS Simulator shortly.

Specifying a device #

You can specify the device the simulator should run with the --simulator flag, followed by the device name as a string. The default is "iPhone 6". If you wish to run your app on an iPhone 4s, just run react-native run-ios --simulator="iPhone 4s".

The device names correspond to the list of devices available in Xcode. You can check your available devices by running xcrun simctl list devices from the console.

You can edit the content above on GitHub and send us a pull request!

Settings #

Methods #

static get(key) #

static set(settings) #

static watchKeys(keys, callback) #

static clearWatch(watchId) #

Properties #

You can edit the content above on GitHub and send us a pull request!

Settings #

Methods #

static get(key) #

static set(settings) #

static watchKeys(keys, callback) #

static clearWatch(watchId) #

Properties #

You can edit the content above on GitHub and send us a pull request!

Shadow Props #

Props #

iosshadowColor color #

Sets the drop shadow color

iosshadowOffset {width: number, height: number} #

Sets the drop shadow offset

iosshadowOpacity number #

Sets the drop shadow opacity (multiplied by the color's alpha component)

iosshadowRadius number #

Sets the drop shadow blur radius

You can edit the content above on GitHub and send us a pull request!

Shadow Props #

Props #

iosshadowColor color #

Sets the drop shadow color

iosshadowOffset {width: number, height: number} #

Sets the drop shadow offset

iosshadowOpacity number #

Sets the drop shadow opacity (multiplied by the color's alpha component)

iosshadowRadius number #

Sets the drop shadow blur radius

You can edit the content above on GitHub and send us a pull request!

SnapshotViewIOS #

Props #

onSnapshotReady function #

testIdentifier string #

You can edit the content above on GitHub and send us a pull request!

SnapshotViewIOS #

Props #

onSnapshotReady function #

testIdentifier string #

You can edit the content above on GitHub and send us a pull request!

StatusBarIOS #

Use StatusBar for mutating the status bar.

You can edit the content above on GitHub and send us a pull request!

StatusBarIOS #

Use StatusBar for mutating the status bar.

You can edit the content above on GitHub and send us a pull request!

Transforms #

Props #

decomposedMatrix DecomposedMatrixPropType #

transform [{perspective: number}, {rotate: string}, {rotateX: string}, {rotateY: string}, {rotateZ: string}, {scale: number}, {scaleX: number}, {scaleY: number}, {translateX: number}, {translateY: number}, {skewX: string}, {skewY: string}] #

transformMatrix TransformMatrixPropType #

You can edit the content above on GitHub and send us a pull request!

Transforms #

Props #

decomposedMatrix DecomposedMatrixPropType #

transform [{perspective: number}, {rotate: string}, {rotateX: string}, {rotateY: string}, {rotateZ: string}, {scale: number}, {scaleX: number}, {scaleY: number}, {translateX: number}, {translateY: number}, {skewX: string}, {skewY: string}] #

transformMatrix TransformMatrixPropType #

You can edit the content above on GitHub and send us a pull request!

React Native Versions

React Native follows a monthly release train. Every month, a new branch created off master enters the Release Candidate phase, and the previous Release Candidate branch is released and considered stable.

Current Version (Stable)

currentDocumentation

This is the version that is configured automatically when you run react-native init. We highly recommend using the current version of React Native when starting a new project.

If you have an existing project that uses React Native, read the release notes to learn about new features and fixes. You can follow our guide to upgrade your app to the latest version.

Pre-release Versions

masterDocumentation
0.42-RCDocumentationRelease Notes
0.41-RCDocumentationRelease Notes
0.40-RCDocumentationRelease Notes
0.39-RCDocumentationRelease Notes
0.38-RCDocumentationRelease Notes
0.37-RCDocumentationRelease Notes
0.36-RCDocumentationRelease Notes
0.35-RCDocumentationRelease Notes
0.34-RCDocumentationRelease Notes
0.33-RCDocumentationRelease Notes
0.32-RCDocumentationRelease Notes
0.31-RCDocumentationRelease Notes
0.30-RCDocumentationRelease Notes
0.29-RCDocumentationRelease Notes
0.28-RCDocumentationRelease Notes
0.27-RCDocumentationRelease Notes
0.26-RCDocumentationRelease Notes
0.25-RCDocumentationRelease Notes
0.24-RCDocumentationRelease Notes
0.23-RCDocumentationRelease Notes
0.22-RCDocumentationRelease Notes
0.21-RCDocumentationRelease Notes
0.20-RCDocumentationRelease Notes
0.19-RCDocumentationRelease Notes
0.18-RCDocumentationRelease Notes

For those who live on the bleeding edge. Only recommended if you're actively contributing code to React Native, or if you need to verify how your application behaves in an upcoming release.

Past Versions

You can find past versions of React Native on GitHub. The release notes can be useful if you would like to learn when a specific feature or fix was released.

You can also view the docs for a particular version of React Native by clicking on the Docs link next to the release in this page. You can come back to this page and switch the version of the docs you're reading at any time by clicking on the version number at the top of the page.

React Native Versions

React Native follows a monthly release train. Every month, a new branch created off master enters the Release Candidate phase, and the previous Release Candidate branch is released and considered stable.

Current Version (Stable)

currentDocumentation

This is the version that is configured automatically when you run react-native init. We highly recommend using the current version of React Native when starting a new project.

If you have an existing project that uses React Native, read the release notes to learn about new features and fixes. You can follow our guide to upgrade your app to the latest version.

Pre-release Versions

masterDocumentation
0.42-RCDocumentationRelease Notes
0.41-RCDocumentationRelease Notes
0.40-RCDocumentationRelease Notes
0.39-RCDocumentationRelease Notes
0.38-RCDocumentationRelease Notes
0.37-RCDocumentationRelease Notes
0.36-RCDocumentationRelease Notes
0.35-RCDocumentationRelease Notes
0.34-RCDocumentationRelease Notes
0.33-RCDocumentationRelease Notes
0.32-RCDocumentationRelease Notes
0.31-RCDocumentationRelease Notes
0.30-RCDocumentationRelease Notes
0.29-RCDocumentationRelease Notes
0.28-RCDocumentationRelease Notes
0.27-RCDocumentationRelease Notes
0.26-RCDocumentationRelease Notes
0.25-RCDocumentationRelease Notes
0.24-RCDocumentationRelease Notes
0.23-RCDocumentationRelease Notes
0.22-RCDocumentationRelease Notes
0.21-RCDocumentationRelease Notes
0.20-RCDocumentationRelease Notes
0.19-RCDocumentationRelease Notes
0.18-RCDocumentationRelease Notes

For those who live on the bleeding edge. Only recommended if you're actively contributing code to React Native, or if you need to verify how your application behaves in an upcoming release.

Past Versions

You can find past versions of React Native on GitHub. The release notes can be useful if you would like to learn when a specific feature or fix was released.

You can also view the docs for a particular version of React Native by clicking on the Docs link next to the release in this page. You can come back to this page and switch the version of the docs you're reading at any time by clicking on the version number at the top of the page.

Who's using React Native?

Thousands of apps are using React Native, from established Fortune 500 companies to hot new startups. If you're curious to see what can be accomplished with React Native, check out these apps!

Vogue

Vogue

iOS

Some of these are hybrid native/React Native apps. If you built a popular application using React Native, we'd love to have your app on this showcase. Check out the guidelines on GitHub to update this page.

Also, a curated list of open source React Native apps is being kept by React Native News.

Who's using React Native?

Thousands of apps are using React Native, from established Fortune 500 companies to hot new startups. If you're curious to see what can be accomplished with React Native, check out these apps!

Vogue

Vogue

iOS

Some of these are hybrid native/React Native apps. If you built a popular application using React Native, we'd love to have your app on this showcase. Check out the guidelines on GitHub to update this page.

Also, a curated list of open source React Native apps is being kept by React Native News.

Need help?

At Facebook, there are dozens of engineers who work on React Native full-time. But there are far more people in the community who make key contributions and fix things. So if you need help with your React Native app, the right place to go depends on the type of help that you need.

Browse the docs

Find what you're looking for in our detailed documentation and guides.

Explore samples

Take apart these fully built applications, and get some inspiration for your own.

Stay up to date

Find out what's happening in the world of React Native.

Join the community

Connect with other React Native developers. Show off your project, or ask how other people solved similar problems.

  • Frequently Asked Questions

    Many React Native users are active on Stack Overflow. Browse existing questions, or ask your own technical question.

  • React Native Community

    If you have an open-ended question or you just want to get a general sense of what React Native folks talk about, check out the React Native Community Facebook group. It has thousands of developers and almost all posts get a response.

  • Reactiflux Chat

    If you need an answer right away, check out the #react-native channel. There are usually a number of React Native experts there who can help out or point you to somewhere you might want to look.

Contribute

React Native is open source! Issues and pull requests are welcome.

  • Get Involved

    If you want to contribute, take a look at the list of good first tasks on GitHub.

  • Feature Requests

    If you have a feature request, add it to the list or upvote a similar one. The voting system helps surface which issues are most important to the community.

  • Report a Bug

    If you have discovered a bug in React Native, consider submitting a pull request with a fix. If you don't think you can fix it yourself, you can open an issue on GitHub.

Need help?

At Facebook, there are dozens of engineers who work on React Native full-time. But there are far more people in the community who make key contributions and fix things. So if you need help with your React Native app, the right place to go depends on the type of help that you need.

Browse the docs

Find what you're looking for in our detailed documentation and guides.

Explore samples

Take apart these fully built applications, and get some inspiration for your own.

Stay up to date

Find out what's happening in the world of React Native.

Join the community

Connect with other React Native developers. Show off your project, or ask how other people solved similar problems.

  • Frequently Asked Questions

    Many React Native users are active on Stack Overflow. Browse existing questions, or ask your own technical question.

  • React Native Community

    If you have an open-ended question or you just want to get a general sense of what React Native folks talk about, check out the React Native Community Facebook group. It has thousands of developers and almost all posts get a response.

  • Reactiflux Chat

    If you need an answer right away, check out the #react-native channel. There are usually a number of React Native experts there who can help out or point you to somewhere you might want to look.

Contribute

React Native is open source! Issues and pull requests are welcome.

  • Get Involved

    If you want to contribute, take a look at the list of good first tasks on GitHub.

  • Feature Requests

    If you have a feature request, add it to the list or upvote a similar one. The voting system helps surface which issues are most important to the community.

  • Report a Bug

    If you have discovered a bug in React Native, consider submitting a pull request with a fix. If you don't think you can fix it yourself, you can open an issue on GitHub.

React Native Versions

React Native follows a monthly release train. Every month, a new branch created off master enters the Release Candidate phase, and the previous Release Candidate branch is released and considered stable.

Current Version (Stable)

currentDocumentation

This is the version that is configured automatically when you run react-native init. We highly recommend using the current version of React Native when starting a new project.

If you have an existing project that uses React Native, read the release notes to learn about new features and fixes. You can follow our guide to upgrade your app to the latest version.

Pre-release Versions

masterDocumentation
0.42-RCDocumentationRelease Notes
0.41-RCDocumentationRelease Notes
0.40-RCDocumentationRelease Notes
0.39-RCDocumentationRelease Notes
0.38-RCDocumentationRelease Notes
0.37-RCDocumentationRelease Notes
0.36-RCDocumentationRelease Notes
0.35-RCDocumentationRelease Notes
0.34-RCDocumentationRelease Notes
0.33-RCDocumentationRelease Notes
0.32-RCDocumentationRelease Notes
0.31-RCDocumentationRelease Notes
0.30-RCDocumentationRelease Notes
0.29-RCDocumentationRelease Notes
0.28-RCDocumentationRelease Notes
0.27-RCDocumentationRelease Notes
0.26-RCDocumentationRelease Notes
0.25-RCDocumentationRelease Notes
0.24-RCDocumentationRelease Notes
0.23-RCDocumentationRelease Notes
0.22-RCDocumentationRelease Notes
0.21-RCDocumentationRelease Notes
0.20-RCDocumentationRelease Notes
0.19-RCDocumentationRelease Notes
0.18-RCDocumentationRelease Notes

For those who live on the bleeding edge. Only recommended if you're actively contributing code to React Native, or if you need to verify how your application behaves in an upcoming release.

Past Versions

You can find past versions of React Native on GitHub. The release notes can be useful if you would like to learn when a specific feature or fix was released.

You can also view the docs for a particular version of React Native by clicking on the Docs link next to the release in this page. You can come back to this page and switch the version of the docs you're reading at any time by clicking on the version number at the top of the page.

React Native Versions

React Native follows a monthly release train. Every month, a new branch created off master enters the Release Candidate phase, and the previous Release Candidate branch is released and considered stable.

Current Version (Stable)

currentDocumentation

This is the version that is configured automatically when you run react-native init. We highly recommend using the current version of React Native when starting a new project.

If you have an existing project that uses React Native, read the release notes to learn about new features and fixes. You can follow our guide to upgrade your app to the latest version.

Pre-release Versions

masterDocumentation
0.42-RCDocumentationRelease Notes
0.41-RCDocumentationRelease Notes
0.40-RCDocumentationRelease Notes
0.39-RCDocumentationRelease Notes
0.38-RCDocumentationRelease Notes
0.37-RCDocumentationRelease Notes
0.36-RCDocumentationRelease Notes
0.35-RCDocumentationRelease Notes
0.34-RCDocumentationRelease Notes
0.33-RCDocumentationRelease Notes
0.32-RCDocumentationRelease Notes
0.31-RCDocumentationRelease Notes
0.30-RCDocumentationRelease Notes
0.29-RCDocumentationRelease Notes
0.28-RCDocumentationRelease Notes
0.27-RCDocumentationRelease Notes
0.26-RCDocumentationRelease Notes
0.25-RCDocumentationRelease Notes
0.24-RCDocumentationRelease Notes
0.23-RCDocumentationRelease Notes
0.22-RCDocumentationRelease Notes
0.21-RCDocumentationRelease Notes
0.20-RCDocumentationRelease Notes
0.19-RCDocumentationRelease Notes
0.18-RCDocumentationRelease Notes

For those who live on the bleeding edge. Only recommended if you're actively contributing code to React Native, or if you need to verify how your application behaves in an upcoming release.

Past Versions

You can find past versions of React Native on GitHub. The release notes can be useful if you would like to learn when a specific feature or fix was released.

You can also view the docs for a particular version of React Native by clicking on the Docs link next to the release in this page. You can come back to this page and switch the version of the docs you're reading at any time by clicking on the version number at the top of the page.