Быстрый старт на React Native
Какие горизонты открывает React? Single Page Application (и веб-приложения, и десктопные приложения на Electron) — это цветочки. Очень заманчиво выглядит разработка мобильных приложений на React Native. Лозунг «learn once, write anywhere» стоит того, чтобы приложить некоторые усилия. Go!
13 марта объявлено стабильным чудесное решение:
Многие разработчики сталкиваются с проблемой установки и настройки существующих зависимостей React Native, особенно для Android. С помощью Create React Native App нет необходимости использовать XCode или Android Studio, и вы можете разрабатывать для своего iOS-устройства, используя Linux или Windows. Это достигается при помощи приложения Expo, которое загружает и запускает проекты CRNA, написанные на чистом JavaScript без компиляции любого собственного кода.
CRNA повторяет идею Create React App (CRA). Никакой настройки окружения — всё готово «из коробки»: запуск тестов, запуск в режиме разработки, боевая сборка и деплой.
$ npm i -g create-react-native-app $ create-react-native-app my-app $ cd my-app $ npm start
Как видно, нужно выполнить несколько условий: установить управляющую оболочку Expo на мобильник, запустить тестируемое приложение через QR-код, при этом мобильник должен находиться в одной локальной сети с вашим компом разработчика.
Можно ещё проще. Подключите мобильник USB-шнурком, и выполните:
$ npm run android
Оно само поставит оболочку Expo на мобильник и запустит тестируемое приложение. Дальше горячая перезагрузка работает почти так же быстро, как при разработке веб-приложения на CRA. Магия!
На Ubuntu/Windows оно доступно только для подключенных Android/iOS устройств; но на Mac-е работает и вовсе без мобильника — на симуляторе iOS:
$ npm run ios
Опционально можно установить на комп Expo XDE:
С помощью этого инструмента также можно запускать тестируемое приложение, при этом отображается лог с мобильного устройства — жирный плюс; но горячая перезагрузка работает медленно, видимо приложение пересобирается каждый раз полностью. UPDATE Нужно вызвать меню разработчика (буквально встряхнуть мобилку), и выбрать «Enable Hot Reloading». При этом выключите Live Reload — оба варианта вместе не поддерживаются.
UPDATE Mac не нужен для разработки iOS-версии; просто подключите iOS-устройство и наслаждайтесь процессом на Ubuntu/Windows (спасибо, andreylat).
Get Started with Windows
This guide will help you get started on setting up your very first React Native for Windows app.
Make sure you have installed all of the development dependencies.
For information around how to set up React Native, see the React Native Getting Started Guide.
Install React Native for Windows
Remember to call react-native init from the place you want your project directory to live.
npx react-native init --template react-native@^0.67.0
To create TypeScript template, run npx react-native init —template react-native-template-typescript .
Navigate into this newly created directory
Once your project has been initialized, React Native will have created a new sub directory where all your generated files live.
cd projectName
Install the Windows extension
Lastly, install the React Native for Windows packages.
npx react-native-windows-init --overwrite
The —overwrite flag copies a custom metro.config.js file. If you are starting a new app, this should have no impact. If you are adding Windows to your existing app and you have modified the metro.config.js file, please back up your changes, run the command and copy over to take effect.
For information on the options that react-native-windows-init takes see React Native Windows Init CLI.
Running a React Native Windows App
Make sure a browser is launched and running before running a React Native Windows app. Also ensure your system meets all the requirements to build a Windows app as well.
- Without Using Visual Studio In your React Native Windows project directory, run:
npx react-native run-windows
-
From the root of the project directory, run the following script which will automatically link your app’s dependencies:
npx react-native autolink-windows
- Open your applications folder in VS Code.
- Install the React Native Tools plugin for VS Code.
- Create a new file in the applications root directory, .vscode/launch.json and paste the following configuration:
"version": "0.2.0", "configurations": [ "name": "Debug Windows", "cwd": "$", "type": "reactnative", "request": "launch", "platform": "windows" > ] >
- Press F5 or navigate to the debug menu (alternatively press Ctrl+Shift+D ) and in the Debug drop-down select «Debug Windows» and press the green arrow to run the application.
Authoring Native Modules
Building a standalone React Native Windows App
Follow these steps to build a version of your app that you can install or publish to the store. This version will package your bundle and assets into the APPX package so you don’t need to run Metro.
- Open the solution in Visual Studio
- Select the Release configuration from the Configuration Manager drop-down.
- Build the solution. You can now launch without first launching Metro.
- If you want to build an APPX package to share or publish, use the Project >Publish >Create App Packages. option.
The Debug configuration uses the Web Debugger by default, which means the application’s JavaScript code runs in Chrome.
If you’re getting different runtime behavior between the Release and Debug configurations, consider disabling the UseWebDebugger setting in App.cpp or App.xaml.cs to get the same behavior in the Debug configuration.
React Native установка, настройка инструментария и первый запуск

Доброе время суток, друзья! В этой статье я бы хотел поделиться опытом создания и настройки своего первого приложения на React Native. Зачем вообще может понадобиться React Native, мне кажется объяснять не стоит, но все же хотелось бы сказать пару слов, зачем это понадобилось мне.
В процессе работы у меня появилась вынужденная необходимость создания несложного мобильного приложения, и, с учетом того, что я все время занимаюсь разработкой приложений и сайтов в сети интернет и использую в своей работе, как правило, PHP и Javascript, то создание мобильного приложения для смартфона, да еще к тому же сразу для двух платформ: IOS и Android, для меня показалось сомнительной, хоть и интересной задачей. И, как не удивительно, React Native в моем случае показался единственным реальным и рабочим инструментом, который к тому же осуществляет поддержку достаточно большого количества мобильных устройств. Заявленная поддержка – это Android 4.1 (API 16) и >= iOS 8.0. А это порядка 98% пользователей Android и более 90% пользователей IOS.
Что потребуется для установки React Native, запуска и работы с приложением?
К счастью, запуск и настройка инструментария для создания своего приложения достаточно просты. Все что, потребуется – это скачать приложение для вашего телефона, которое называется Expo, редактор кода и терминал. Данное приложение доступно в Google Play и App Store для скачивания. Если вы не хотите устанавливать данное приложение на ваш телефон, то вы также можете зарегистрироваться на сайте expo.io, где у вас будет возможность разрабатывать ваше приложение через ваш браузер.
Сразу хочу сказать, что когда я скачал данное приложение для IPhone, то для его запуска потребовалось добавить проект в «мои проекты» на expo.io. На Android все было проще, поскольку было достаточно просканировать QR код, который любезно сгенерировала мне утилита create-react-native-app.
Важно: требуется понимать, что у вас должен быть установлен node.js на вашем компьютере и npm.
Наши дальнейшие действия таковы:
- 1 — заходим в терминал и устанавливаем create-react-native-app глобально, если он не установлен, командой: npm install -g create-react-native-app
- 2 — затем создаем проект вводом команды: create-react-native-app MyApp
- 3 — переходим в папку проекта: cd MyApp
- 4 — запускаем проект: npm start
Примерный результат запуска приложения на вашем устройстве (рис.1)

Рис.1
Все готово. Теперь можно сгенерировать QR код для вашего телефона, просканировать его и можно писать нативное приложение на Javascript для ваших мобильных устройств.
Setting up the development environment
This page will help you install and build your first React Native app.
If you are new to mobile development, the easiest way to get started is with Expo Go. Expo is a set of tools and services built around React Native and, while it has many features, the most relevant feature for us right now is that it can get you writing a React Native app within minutes. You will only need a recent version of Node.js and a phone or emulator. If you’d like to try out React Native directly in your web browser before installing any tools, you can try out Snack.
If you are already familiar with mobile development, you may want to use React Native CLI. It requires Xcode or Android Studio to get started. If you already have one of these tools installed, you should be able to get up and running within a few minutes. If they are not installed, you should expect to spend about an hour installing and configuring them.
- Expo Go Quickstart
- React Native CLI Quickstart
Run the following command to create a new React Native project called «AwesomeProject»:
npx create-expo-app AwesomeProject cd AwesomeProject npx expo start
yarn create expo-app AwesomeProject cd AwesomeProject yarn expo start
This will start a development server for you.
Running your React Native application
Install the Expo Go app on your iOS or Android phone and connect to the same wireless network as your computer. On Android, use the Expo Go app to scan the QR code from your terminal to open your project. On iOS, use the built-in QR code scanner of the default iOS Camera app.
Modifying your app
Now that you have successfully run the app, let’s modify it. Open App.js in your text editor of choice and edit some lines. The application should reload automatically once you save your changes.
That’s it!
Congratulations! You’ve successfully run and modified your first React Native app.

Now what?
Expo also has docs you can reference if you have questions specific to the tool. You can also ask for help on the Expo Discord.
If you have a problem with Expo, before creating a new issue, please see if there’s an existing issue about it in the Expo issues.
If you’re curious to learn more about React Native, check out the Introduction to React Native.
Running your app on a simulator or virtual device
Expo Go allows you to run your React Native app on a physical device without installing iOS and Android native SDKs. If you want to run your app on the iOS Simulator or an Android Virtual Device, please refer to the instructions for «React Native CLI Quickstart» to learn how to install Xcode or set up your Android development environment.
Once you’ve set these up, you can launch your app on an Android Virtual Device by running npm run android , or on the iOS Simulator by running npm run ios (macOS only).
Caveats
The Expo Go app is a great tool to get started — it exists to help developers quickly get projects off the ground, to experiment with ideas (such as on Snack) and share their work with minimal friction. Expo Go makes this possible by including a feature-rich native runtime made up of every module in the Expo SDK, so all you need to do to use a module is install the package with npx expo install and reload your app.
The tradeoff is that the Expo Go app does not allow you to add custom native code — you can only use native modules built into the Expo SDK. There are many great libraries available outside of the Expo SDK, and you may even want to build your own native library. You can leverage these libraries with development builds, or by using «prebuild» to generate the native projects, or both. Learn more about adding native code to projects created with create-expo-app .
create-expo-app configures your project to use the most recent React Native version that is supported by the Expo SDK. The Expo Go app usually gains support for a given React Native version with new SDK versions (released quarterly). You can check this document to find out what versions are supported.
If you’re integrating React Native into an existing project, you can use the Expo SDK and development builds, but you will need to set up a native development environment. Select «React Native CLI Quickstart» above for instructions on configuring a native build environment for React Native.
Follow these instructions if you need to build native code in your project. For example, if you are integrating React Native into an existing application, or if you ran «prebuild» from Expo to generate your project’s native code, you’ll need this section.
The instructions are a bit different depending on your development operating system, and whether you want to start developing for iOS or Android. If you want to develop for both Android and iOS, that’s fine — you can pick one to start with, since the setup is a bit different.
Development OS
Target OS
Installing dependencies
You will need Node, Watchman, the React Native command line interface, a JDK, and Android Studio.
While you can use any editor of your choice to develop your app, you will need to install Android Studio in order to set up the necessary tooling to build your React Native app for Android.
Node & Watchman
We recommend installing Node and Watchman using Homebrew. Run the following commands in a Terminal after installing Homebrew:
brew install node brew install watchman
If you have already installed Node on your system, make sure it is Node 16 or newer.
Watchman is a tool by Facebook for watching changes in the filesystem. It is highly recommended you install it for better performance.
Java Development Kit
We recommend installing the OpenJDK distribution called Azul Zulu using Homebrew. Run the following commands in a Terminal after installing Homebrew:
brew tap homebrew/cask-versions brew install --cask zulu11 # Get path to where cask was installed to double-click installer brew info --cask zulu11
After you install the JDK, update your JAVA_HOME environment variable. If you used above steps, JDK will likely be at /Library/Java/JavaVirtualMachines/zulu-11.jdk/Contents/Home
The Zulu OpenJDK distribution offers JDKs for both Intel and M1 Macs. This will make sure your builds are faster on M1 Macs compared to using an Intel-based JDK.
If you have already installed JDK on your system, we recommend JDK 11. You may encounter problems using higher JDK versions.
Android development environment
Setting up your development environment can be somewhat tedious if you’re new to Android development. If you’re already familiar with Android development, there are a few things you may need to configure. In either case, please make sure to carefully follow the next few steps.
1. Install Android Studio
Download and install Android Studio. While on Android Studio installation wizard, make sure the boxes next to all of the following items are checked:
- Android SDK
- Android SDK Platform
- Android Virtual Device
Then, click «Next» to install all of these components.
If the checkboxes are grayed out, you will have a chance to install these components later on.
Once setup has finalized and you’re presented with the Welcome screen, proceed to the next step.
2. Install the Android SDK
Android Studio installs the latest Android SDK by default. Building a React Native app with native code, however, requires the Android 13 (Tiramisu) SDK in particular. Additional Android SDKs can be installed through the SDK Manager in Android Studio.
To do that, open Android Studio, click on «More Actions» button and select «SDK Manager».

The SDK Manager can also be found within the Android Studio «Settings» dialog, under Languages & Frameworks → Android SDK.
Select the «SDK Platforms» tab from within the SDK Manager, then check the box next to «Show Package Details» in the bottom right corner. Look for and expand the Android 13 (Tiramisu) entry, then make sure the following items are checked:
- Android SDK Platform 33
- Intel x86 Atom_64 System Image or Google APIs Intel x86 Atom System Image or (for Apple M1 Silicon) Google APIs ARM 64 v8a System Image
Next, select the «SDK Tools» tab and check the box next to «Show Package Details» here as well. Look for and expand the «Android SDK Build-Tools» entry, then make sure that 33.0.0 is selected.
Finally, click «Apply» to download and install the Android SDK and related build tools.
3. Configure the ANDROID_HOME environment variable
The React Native tools require some environment variables to be set up in order to build apps with native code.
Add the following lines to your ~/.zprofile or ~/.zshrc (if you are using bash , then ~/.bash_profile or ~/.bashrc ) config file:
export ANDROID_HOME=$HOME/Library/Android/sdk export PATH=$PATH:$ANDROID_HOME/emulator export PATH=$PATH:$ANDROID_HOME/platform-tools
Run source ~/.zprofile (or source ~/.bash_profile for bash ) to load the config into your current shell. Verify that ANDROID_HOME has been set by running echo $ANDROID_HOME and the appropriate directories have been added to your path by running echo $PATH .
Please make sure you use the correct Android SDK path. You can find the actual location of the SDK in the Android Studio «Settings» dialog, under Languages & Frameworks → Android SDK.
React Native Command Line Interface
React Native has a built-in command line interface. Rather than install and manage a specific version of the CLI globally, we recommend you access the current version at runtime using npx , which ships with Node.js. With npx react-native , the current stable version of the CLI will be downloaded and executed at the time the command is run.
Creating a new application
If you previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:
npm uninstall -g react-native-cli @react-native-community/cli
React Native has a built-in command line interface, which you can use to generate a new project. You can access it without installing anything globally using npx , which ships with Node.js. Let’s create a new React Native project called «AwesomeProject»:
npx react-native@latest init AwesomeProject
This is not necessary if you are integrating React Native into an existing application, if you «ejected» from Expo, or if you’re adding Android support to an existing React Native project (see Integration with Existing Apps). You can also use a third-party CLI to init your React Native app, such as Ignite CLI.
[Optional] Using a specific version or template
If you want to start a new project with a specific React Native version, you can use the —version argument:
npx react-native@X.XX.X init AwesomeProject --version X.XX.X
You can also start a project with a custom React Native template with the —template argument.
Preparing the Android device
You will need an Android device to run your React Native Android app. This can be either a physical Android device, or more commonly, you can use an Android Virtual Device which allows you to emulate an Android device on your computer.
Either way, you will need to prepare the device to run Android apps for development.
Using a physical device
If you have a physical Android device, you can use it for development in place of an AVD by plugging it in to your computer using a USB cable and following the instructions here.
Using a virtual device
If you use Android Studio to open ./AwesomeProject/android , you can see the list of available Android Virtual Devices (AVDs) by opening the «AVD Manager» from within Android Studio. Look for an icon that looks like this:
If you have recently installed Android Studio, you will likely need to create a new AVD. Select «Create Virtual Device. «, then pick any Phone from the list and click «Next», then select the Tiramisu API Level 33 image.
Click «Next» then «Finish» to create your AVD. At this point you should be able to click on the green triangle button next to your AVD to launch it, then proceed to the next step.
Running your React Native application
Step 1: Start Metro
First, you will need to start Metro, the JavaScript bundler that ships with React Native. Metro «takes in an entry file and various options, and returns a single JavaScript file that includes all your code and its dependencies.»—Metro Docs
To start Metro, run following command inside your React Native project folder:
npm start