From e72805f3bfc85dcf98f592b15403dcfc254d1bc1 Mon Sep 17 00:00:00 2001 From: TatianaKapos Date: Mon, 19 Aug 2024 14:54:58 -0700 Subject: [PATCH 1/8] update website to 0.75 --- docs/getting-started.md | 6 +- docs/native-api/HttpSettings-api-windows.md | 22 + docs/native-api/QuirkSettings-api-windows.md | 2 +- .../ReactInstanceSettings-api-windows.md | 1 + .../ReactPointerEventArgs-api-windows.md | 4 +- docs/native-api/index-api-windows.md | 1 + website/.unbroken_exclusions | 41 ++ website/pages/en/support.js | 6 +- website/siteConfig.js | 2 +- .../version-0.75/autolink-windows-cli.md | 38 + .../version-0.75/codegen-windows-cli.md | 34 + .../version-0.75/debugging-javascript.md | 446 ++++++++++++ .../version-0.75/getting-started.md | 139 ++++ website/versioned_docs/version-0.75/hermes.md | 120 ++++ .../version-0.75/init-windows-cli.md | 50 ++ .../native-api/HttpSettings-api-windows.md | 23 + .../ReactInstanceSettings-api-windows.md | 231 ++++++ .../native-api/index-api-windows.md | 130 ++++ .../version-0.75/native-code.md | 76 ++ .../native-modules-autolinking.md | 53 ++ .../version-0.75/native-modules-setup.md | 176 +++++ .../version-0.75/native-modules-using.md | 41 ++ .../version-0.75/nuget-update.md | 93 +++ website/versioned_docs/version-0.75/nuget.md | 61 ++ .../version-0.75/react-native-windows-cli.md | 33 + .../versioned_docs/version-0.75/releases.md | 16 + .../version-0.75/run-windows-cli.md | 56 ++ .../versioned_docs/version-0.75/setup-ci.md | 117 +++ .../version-0.75/upgrade-app.md | 25 + .../version-0.75/view-managers.md | 671 ++++++++++++++++++ .../version-0.75-sidebars.json | 90 +++ website/versions.json | 1 + 32 files changed, 2795 insertions(+), 10 deletions(-) create mode 100644 docs/native-api/HttpSettings-api-windows.md create mode 100644 website/versioned_docs/version-0.75/autolink-windows-cli.md create mode 100644 website/versioned_docs/version-0.75/codegen-windows-cli.md create mode 100644 website/versioned_docs/version-0.75/debugging-javascript.md create mode 100644 website/versioned_docs/version-0.75/getting-started.md create mode 100644 website/versioned_docs/version-0.75/hermes.md create mode 100644 website/versioned_docs/version-0.75/init-windows-cli.md create mode 100644 website/versioned_docs/version-0.75/native-api/HttpSettings-api-windows.md create mode 100644 website/versioned_docs/version-0.75/native-api/ReactInstanceSettings-api-windows.md create mode 100644 website/versioned_docs/version-0.75/native-api/index-api-windows.md create mode 100644 website/versioned_docs/version-0.75/native-code.md create mode 100644 website/versioned_docs/version-0.75/native-modules-autolinking.md create mode 100644 website/versioned_docs/version-0.75/native-modules-setup.md create mode 100644 website/versioned_docs/version-0.75/native-modules-using.md create mode 100644 website/versioned_docs/version-0.75/nuget-update.md create mode 100644 website/versioned_docs/version-0.75/nuget.md create mode 100644 website/versioned_docs/version-0.75/react-native-windows-cli.md create mode 100644 website/versioned_docs/version-0.75/releases.md create mode 100644 website/versioned_docs/version-0.75/run-windows-cli.md create mode 100644 website/versioned_docs/version-0.75/setup-ci.md create mode 100644 website/versioned_docs/version-0.75/upgrade-app.md create mode 100644 website/versioned_docs/version-0.75/view-managers.md create mode 100644 website/versioned_sidebars/version-0.75-sidebars.json diff --git a/docs/getting-started.md b/docs/getting-started.md index 5b6aeaeef..f556cff28 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -23,7 +23,7 @@ Remember to call `@react-native-community/cli init` from the place you want your ```bat -npx --yes @react-native-community/cli@next init --version "nightly" +npx --yes @react-native-community/cli@next init --version "latest" ``` ### Navigate into this newly created directory @@ -47,13 +47,13 @@ cd ```bat -yarn add react-native-windows@canary +yarn add react-native-windows@latest ``` ```bat -npm install --save react-native-windows@canary +npm install --save react-native-windows@latest ``` diff --git a/docs/native-api/HttpSettings-api-windows.md b/docs/native-api/HttpSettings-api-windows.md new file mode 100644 index 000000000..92aa192f4 --- /dev/null +++ b/docs/native-api/HttpSettings-api-windows.md @@ -0,0 +1,22 @@ +--- +id: HttpSettings +title: HttpSettings +--- + +Kind: `class` + + + +Provides settings for Http functionality. + + + +## Methods +### SetDefaultUserAgent +`static` void **`SetDefaultUserAgent`**([`ReactInstanceSettings`](ReactInstanceSettings) settings, string userAgent) + +Configures the react instance to use a user-agent header by default on http requests. + + + + diff --git a/docs/native-api/QuirkSettings-api-windows.md b/docs/native-api/QuirkSettings-api-windows.md index 31d2ec6de..1e3caad69 100644 --- a/docs/native-api/QuirkSettings-api-windows.md +++ b/docs/native-api/QuirkSettings-api-windows.md @@ -28,7 +28,7 @@ Runtime setting allowing Networking (HTTP, WebSocket) connections to skip certif > **EXPERIMENTAL** -By default `react-native-windows` will handle various back events and forward them to JavaScript. Setting this to [`BackNavigationHandlerKind.Native`](BackNavigationHandlerKind) prevents `react-native-windows` from handling these events, including forwarding to JavaScript. This will allow applications to handle back navigation in native code, but will prevent the `BackHandler` native module from receiving events. +By default `react-native-windows` will handle various back events and forward them to JavaScript. Setting this to [`BackNavigationHandlerKind.Native`](BackNavigationHandlerKind#native) prevents `react-native-windows` from handling these events, including forwarding to JavaScript. This will allow applications to handle back navigation in native code, but will prevent the `BackHandler` native module from receiving events. diff --git a/docs/native-api/ReactInstanceSettings-api-windows.md b/docs/native-api/ReactInstanceSettings-api-windows.md index f2dae8e85..d3dd4c41c 100644 --- a/docs/native-api/ReactInstanceSettings-api-windows.md +++ b/docs/native-api/ReactInstanceSettings-api-windows.md @@ -224,6 +224,7 @@ Type: [`InstanceLoadedEventArgs`](InstanceLoadedEventArgs) ## Referenced by +- [`HttpSettings`](HttpSettings) - [`QuirkSettings`](QuirkSettings) - [`ReactApplication`](ReactApplication) - [`ReactNativeHost`](ReactNativeHost) diff --git a/docs/native-api/ReactPointerEventArgs-api-windows.md b/docs/native-api/ReactPointerEventArgs-api-windows.md index c0efaf5e9..3e931aa2d 100644 --- a/docs/native-api/ReactPointerEventArgs-api-windows.md +++ b/docs/native-api/ReactPointerEventArgs-api-windows.md @@ -17,7 +17,7 @@ Event arguments wrapper for [`IViewManagerWithPointerEvents`](IViewManagerWithPo > **EXPERIMENTAL** -Gets or sets a flag that allows the ReactRootView to handle pointer events even when it does not capture the pointer. This is particularly useful for view managers that seek to capture the pointer to handle move events for a gesture (e.g., dragging), but conditionally may allow the ReactRootView to emit events (e.g., if the [`PointerEventKind.End`](PointerEventKind) event is received before a drag threshold is hit. +Gets or sets a flag that allows the ReactRootView to handle pointer events even when it does not capture the pointer. This is particularly useful for view managers that seek to capture the pointer to handle move events for a gesture (e.g., dragging), but conditionally may allow the ReactRootView to emit events (e.g., if the [`PointerEventKind.End`](PointerEventKind#end) event is received before a drag threshold is hit. ### Args `readonly` [`PointerRoutedEventArgs`](https://docs.microsoft.com/uwp/api/Windows.UI.Xaml.Input.PointerRoutedEventArgs) `Args` @@ -31,7 +31,7 @@ Gets the wrapped routed pointer event. > **EXPERIMENTAL** -Gets or sets the pointer event kind. The only valid override is [`PointerEventKind.CaptureLost`](PointerEventKind) to [`PointerEventKind.End`](PointerEventKind) to handle cases where PointerCaptureLost events on ReactRootView can be safely treated as PointerReleased events, e.g., for pointer events on selectable text. +Gets or sets the pointer event kind. The only valid override is [`PointerEventKind.CaptureLost`](PointerEventKind#capturelost) to [`PointerEventKind.End`](PointerEventKind#end) to handle cases where PointerCaptureLost events on ReactRootView can be safely treated as PointerReleased events, e.g., for pointer events on selectable text. ### Target Object `Target` diff --git a/docs/native-api/index-api-windows.md b/docs/native-api/index-api-windows.md index 5fc254343..78c75d5a4 100644 --- a/docs/native-api/index-api-windows.md +++ b/docs/native-api/index-api-windows.md @@ -82,6 +82,7 @@ sidebar_label: Full reference - [`DynamicAutomationProperties`](DynamicAutomationProperties) - [`DynamicValueProvider`](DynamicValueProvider) - [`GaussianBlurEffect`](GaussianBlurEffect) +- [`HttpSettings`](HttpSettings) - [`InstanceCreatedEventArgs`](InstanceCreatedEventArgs) - [`InstanceDestroyedEventArgs`](InstanceDestroyedEventArgs) - [`InstanceLoadedEventArgs`](InstanceLoadedEventArgs) diff --git a/website/.unbroken_exclusions b/website/.unbroken_exclusions index ad257cf7f..214f188ab 100644 --- a/website/.unbroken_exclusions +++ b/website/.unbroken_exclusions @@ -13,6 +13,7 @@ !versioned_docs/version-0.72/native-api/*-api-windows*.md !versioned_docs/version-0.73/native-api/*-api-windows*.md !versioned_docs/version-0.74/native-api/*-api-windows*.md +!versioned_docs/version-0.75/native-api/*-api-windows*.md # See Issue 410 File not found IReactContext while parsing versioned_docs/version-0.64/native-modules-advanced.md @@ -26,6 +27,46 @@ File not found native-api/IReactContext-api-windows.md while parsing versioned_d File not found native-api/ReactNativeHost-api-windows.md while parsing versioned_docs/version-0.72/native-modules-advanced.md #fix-unbroken.js auto-generated do not edit this line or below +File not found run-windows-cli.md while parsing versioned_docs/version-0.75/autolink-windows-cli.md +File not found run-windows-cli.md while parsing versioned_docs/version-0.75/debugging-javascript.md +File not found getting-started.md while parsing versioned_docs/version-0.75/getting-started.md +File not found run-windows-cli.md while parsing versioned_docs/version-0.75/getting-started.md +File not found native-modules.md while parsing versioned_docs/version-0.75/getting-started.md +File not found rnw-dependencies.md while parsing versioned_docs/version-0.75/getting-started.md +File not found getting-started.md while parsing versioned_docs/version-0.75/hermes.md +File not found rnm-getting-started.md while parsing versioned_docs/version-0.75/hermes.md +File not found run-windows-cli.md while parsing versioned_docs/version-0.75/hermes.md +File not found getting-started.md while parsing versioned_docs/version-0.75/native-code.md +File not found run-windows-cli.md while parsing versioned_docs/version-0.75/native-code.md +File not found native-code-language-choice.md while parsing versioned_docs/version-0.75/native-code.md +File not found run-windows-cli.md while parsing versioned_docs/version-0.75/native-modules-autolinking.md +File not found config.md while parsing versioned_docs/version-0.75/native-modules-autolinking.md +File not found getting-started.md while parsing versioned_docs/version-0.75/native-modules-setup.md +File not found native-modules.md while parsing versioned_docs/version-0.75/native-modules-setup.md +File not found rnw-dependencies.md while parsing versioned_docs/version-0.75/native-modules-setup.md +File not found native-modules-autolinking.md while parsing versioned_docs/version-0.75/native-modules-setup.md +File not found setup-ci.md while parsing versioned_docs/version-0.75/native-modules-setup.md +File not found view-managers.md while parsing versioned_docs/version-0.75/native-modules-setup.md +File not found native-modules-using.md while parsing versioned_docs/version-0.75/native-modules-setup.md +File not found supported-community-modules.md while parsing versioned_docs/version-0.75/native-modules-setup.md +File not found testing.md while parsing versioned_docs/version-0.75/native-modules-setup.md +File not found run-windows-cli.md while parsing versioned_docs/version-0.75/native-modules-using.md +File not found native-modules-autolinking.md while parsing versioned_docs/version-0.75/native-modules-using.md +File not found assets/nuget-update-cpp-project.png while parsing versioned_docs/version-0.75/nuget-update.md +File not found assets/nuget-update-cs-project.png while parsing versioned_docs/version-0.75/nuget-update.md +File not found assets/nuget-update-packages-manager-installed-tab.png while parsing versioned_docs/version-0.75/nuget-update.md +File not found assets/nuget-update-select-package.png while parsing versioned_docs/version-0.75/nuget-update.md +File not found nuget.md while parsing versioned_docs/version-0.75/nuget-update.md +File not found getting-started.md while parsing versioned_docs/version-0.75/nuget.md +File not found nuget-update.md while parsing versioned_docs/version-0.75/nuget.md +File not found managing-cpp-deps.md while parsing versioned_docs/version-0.75/nuget.md +File not found upgrade-app.md while parsing versioned_docs/version-0.75/nuget.md +File not found native-modules-csharp-codegen.md while parsing versioned_docs/version-0.75/nuget.md +File not found supported-community-modules.md while parsing versioned_docs/version-0.75/nuget.md +File not found run-windows-cli.md while parsing versioned_docs/version-0.75/react-native-windows-cli.md +File not found getting-started.md while parsing versioned_docs/version-0.75/view-managers.md +File not found native-modules.md while parsing versioned_docs/version-0.75/view-managers.md +File not found native-modules-setup.md while parsing versioned_docs/version-0.75/view-managers.md File not found getting-started.md while parsing versioned_docs/version-0.74/getting-started.md File not found native-modules.md while parsing versioned_docs/version-0.74/getting-started.md File not found rnw-dependencies.md while parsing versioned_docs/version-0.74/getting-started.md diff --git a/website/pages/en/support.js b/website/pages/en/support.js index ca8237e2f..40c3468ab 100644 --- a/website/pages/en/support.js +++ b/website/pages/en/support.js @@ -16,12 +16,12 @@ The React Native for Windows (RNW) Team strives to provide full support for the | Version | Support Phase | Release Date | Active Support Start | Maintenance Support Start | End of Support | | -- | -- | -- | -- | -- | -- | | [main](https://www.npmjs.com/package/react-native-windows/v/canary) | [Canary](#canary-support) | *N/A* | *N/A* | *N/A* | *N/A* | -| [0.75](https://www.npmjs.com/package/react-native-windows/v/preview) | [Preview](#preview-support) | *TBD* | *TBD* | *TBD* | *TBD* | -| [0.74](https://www.npmjs.com/package/react-native-windows/v/latest) | [Active](#active-support) | 4/29/2024 | 4/29/2024 | *TBD* | *TBD* | +| [0.76](https://www.npmjs.com/package/react-native-windows/v/preview) | [Preview](#preview-support) | *TBD* | *TBD* | *TBD* | *TBD* | +| [0.75](https://www.npmjs.com/package/react-native-windows/v/latest) | [Active](#active-support) | 8/19/2024 | 8/19/2024 | *TBD* | *TBD* | +| [0.74](https://www.npmjs.com/package/react-native-windows/v/v0.74-stable) | [Unsupported](#unsupported) | 4/29/2024 | 4/29/2024 | 9/30/2024 | 11/30/2024 | | [0.73](https://www.npmjs.com/package/react-native-windows/v/v0.73-stable) | [Unsupported](#unsupported) | 12/11/2023 | 12/11/2023 | 5/31/2024 | 7/31/2024 | | [0.72](https://www.npmjs.com/package/react-native-windows/v/v0.72-stable) | [Unsupported](#unsupported) | 06/23/2023 | 06/23/2023 | 01/31/2024 | 03/31/2024 | | [0.71](https://www.npmjs.com/package/react-native-windows/v/v0.71-stable) | [Unsupported](#unsupported) | 01/23/2023 | 01/23/2023 | 07/31/2023 | 09/30/2023 | -| [0.70](https://www.npmjs.com/package/react-native-windows/v/v0.70-stable) | [Unsupported](#unsupported) | 09/12/2022 | 09/12/2022 | 02/28/2023 | 04/30/2023 |
diff --git a/website/siteConfig.js b/website/siteConfig.js index 58c53ce1d..db45a80eb 100644 --- a/website/siteConfig.js +++ b/website/siteConfig.js @@ -8,7 +8,7 @@ // See https://docusaurus.io/docs/site-config for all the possible // site configuration options. -const defaultVersionShown = "0.74"; +const defaultVersionShown = "0.75"; const repoUrl = "https://github.com/microsoft/react-native-windows"; const siteConfig = { diff --git a/website/versioned_docs/version-0.75/autolink-windows-cli.md b/website/versioned_docs/version-0.75/autolink-windows-cli.md new file mode 100644 index 000000000..3a6a56154 --- /dev/null +++ b/website/versioned_docs/version-0.75/autolink-windows-cli.md @@ -0,0 +1,38 @@ +--- +id: version-0.75-autolink-windows-cli +title: react-native autolink-windows +original_id: autolink-windows-cli +--- + +This guide will give you more information on the `autolink-windows` command of the React Native Windows CLI. + +## `autolink-windows` + +The `autolink-windows` CLI command is used to link the native code and build systems for a React Native for Windows app with any native community modules it uses. + +**Note:** Autolinking runs automatically as part of running the [run-windows command](run-windows-cli.md), unless the `--no-autolink` argument is used. + +### Usage +Runs Windows-specific autolinking for your RNW project. + +```bat +npx react-native autolink-windows +``` +### Options + +Here are the options that `react-native autolink-windows` takes: +| Option | Input Type | Description | +|-----------------------|------------|--------------------------------------------------| +| `--logging` | boolean | Verbose output logging | +| `--check` | boolean | Only check whether any autolinked files need to change | +| `--sln` | string | Override the app solution file determined by 'react-native config', i.e. `windows\myApp.sln` | +| `--proj` | string | Override the app project file determined by 'react-native config', i.e. `windows\myApp\myApp.vcxproj` | +| `--no-telemetry` | boolean | Disables sending telemetry that allows analysis of usage and failures of the react-native-windows CLI | +| `-h`, `--help` | boolean | Display help for command | + +This sends telemetry to Microsoft by default. You can prevent the telemetry from being sent by using the `--no-telemetry` command line option. See below for more details. + +The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices. + +This data collection notice only applies to the process of running the react-native-windows CLI commands. + \ No newline at end of file diff --git a/website/versioned_docs/version-0.75/codegen-windows-cli.md b/website/versioned_docs/version-0.75/codegen-windows-cli.md new file mode 100644 index 000000000..f4b0566a1 --- /dev/null +++ b/website/versioned_docs/version-0.75/codegen-windows-cli.md @@ -0,0 +1,34 @@ +--- +id: version-0.75-codegen-windows-cli +title: react-native codegen-windows +original_id: codegen-windows-cli +--- + +This guide will give you more information on the `codegen-windows` command of the React Native Windows CLI. + +## `codegen-windows` + +The `codegen-windows` CLI command is used to generate some necessary Windows-specific native code for native modules. + +### Usage +Runs Windows-specific codegen for native modules. + +```bat +npx react-native codegen-windows +``` +### Options + +Here are the options that `react-native codegen-windows` takes: +| Option | Input Type | Description | +|-----------------------|------------|--------------------------------------------------| +| `--logging` | boolean | Verbose output logging | +| `--check` | boolean | Only check whether any codegen files need to change | +| `--no-telemetry` | boolean | Disables sending telemetry that allows analysis of usage and failures of the react-native-windows CLI | +| `-h`, `--help` | boolean | Display help for command | + +This sends telemetry to Microsoft by default. You can prevent the telemetry from being sent by using the `--no-telemetry` command line option. See below for more details. + +The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices. + +This data collection notice only applies to the process of running the react-native-windows CLI commands. + \ No newline at end of file diff --git a/website/versioned_docs/version-0.75/debugging-javascript.md b/website/versioned_docs/version-0.75/debugging-javascript.md new file mode 100644 index 000000000..4bb0438c6 --- /dev/null +++ b/website/versioned_docs/version-0.75/debugging-javascript.md @@ -0,0 +1,446 @@ +--- +id: version-0.75-debugging-javascript +title: JavaScript Debugging +original_id: debugging-javascript +--- + +This page details how to debug the JavaScript code in your RNW applications, including which tools are supported in which scenarios. You have two different options: *Direct Debugging* and *Web Debugging*. + +> Unless stated otherwise, each of the debugging scenarios detailed below assume you're loading your JS bundle from the Metro Packager, not loading a prebuilt bundle file. + +## Direct Debugging + +*Direct Debugging* is the new JS debugging solution for RN and is the default solution enabled in new RNW projects. + + +Rather than running your app's JS code on an external JS engine (as with Web Debugging), with Direct Debugging you run your app's code on its embedded engine (as normal). You are then able to attach your debugger directly to the embedded engine. + +> Direct Debugging requires the Metro Packager, as Metro provides keys parts of the debugging experience such as JS source mapping. + +### Direct Debugging Tool Support + +| JavaScript Engine | Edge Developer Tools | Visual Studio | Visual Studio Code | Visual Studio Code
w/ React Native Tools | +|:------------------|:-:|:-:|:-:|:-:| +| Hermes (Default) | ✅ | ✅ | ✅ | ✅ | +| Chakra | 🟥 | ✅ | 🟥 | 🟥 | + +> **Important:** Some versions of Hermes have [known issues with direct debugging](https://github.com/microsoft/react-native-windows/issues/12982) that may be fixed, at which point this warning can be removed. In the meantime, **we recommend using Web Debugging**. + +> **Important:** Direct Debugging is relatively new and may still have some rough edges, depending on your choice of engine and debugger. See [Web vs. Direct Debugging](#web-vs-direct-debugging) for details. + +### Step 1: Enable Direct Debugging + +You have two options to enable Direct Debugging: at compile-time in your app's native code or at runtime via the in-app Developer Menu. + +#### Option 1: Setting `UseDirectDebugger` in your native code + +Direct Debugging can be enabled by setting `UseDirectDebugger` property of your app's `InstanceSettings` during startup. + + + + + +##### Modifying your C++ RNW app + +1. You'll want to edit your `App`'s constructor in `App.cpp` with: + +```c++ +InstanceSettings().UseWebDebugger(false); +InstanceSettings().UseDirectDebugger(true); +``` + + + +##### Modifying your C# RNW app + +1. You'll want to edit your `App`'s constructor in `App.xaml.cs` with: + +```csharp +InstanceSettings.UseWebDebugger = false; +InstanceSettings.UseDirectDebugger = true; +``` + + + +2. Then simply re-build and launch your RNW app as usual. + +> For a new RNW app `UseDirectDebugger` defaults to `true` for Debug builds, and `false` for Release builds. + +#### Option 2: Using the Developer Menu + +Direct Debugging can also be enabled at runtime via the in-app Developer Menu. + +1. With your RNW app running, press `Ctrl+Shift+D` to invoke the Developer Menu +2. Click *Enable Direct JS Debugging* + +The app then should automatically refresh with Direct Debugging enabled. + +### Step 2: Connect a debugger + +The next step is to connect with your chosen debugger. + + + + + +#### Using the Edge Developer Tools + +You can direct debug RNW apps using the Hermes JS engine with Edge by using the [Edge Developer Tools](https://learn.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium/). + +> If you use Chrome, the process is similar for using the [Chrome Developer Tools](https://developer.chrome.com/docs/devtools/). + +1. Launch your RNW app (with Direct Debugging enabled and Metro running) +2. In Edge, open the URL `edge://inspect` +3. Make sure the box for *Discover network targets* is checked +4. Click the *Configure...* button next to *Discover network targets* +5. Under *Target discovery settings* add an entry for `localhost:8081` and click *Done* +6. Refresh the `edge://inspect` page +> Watch for a *Hermes React Native* entry to appear in the *Remote Target* section at the bottom of the page. Note that the *Remote Target* section itself may be hidden until a valid target is detected. + +7. Click on the *inspect* link under the *Hermes React Native* entry + +You should now be able to debug your RNW application. To set breakpoints you'll first need to find your app's JS source files via Metro's source map. + +1. Click on the *Sources* tab +2. Press `Ctrl+P` to invoke the *Open* pop-up +3. Find your target source file (manually or by typing its name) and open it +> Make sure that the file you open is being sourced from the source map from Metro, i.e. the file entry is tagged with `localhost:8081` under the file name + +You should now be able to set breakpoints in your app's JS source files. + +> **Important:** The *Filesystem* tab in the left sidebar normally lets you add you app's source folders to the "workspace" for easy browsing. However, files opened from the workspace will not allow you to set breakpoints correctly. You **must** open your app's source via the `Ctrl+P` method above for breakpoints to work. +> +> If you're trying to set a breakpoint and it's not working, double-check that the open file was opened via the source map. The tab's title should appear as an absolute file name, and its tool-tip should show the real path prefixed with `http://localhost:8081/`. + + + +#### Using Visual Studio (Chakra) + +You can direct debug RNW apps using the (default) Chakra JS engine with [Visual Studio](https://visualstudio.microsoft.com/)'s built-in Script debugger. + +1. Make sure you have Visual Studio installed +2. Open your project's Visual Studio solution file (i.e. `MyApp.sln`) +3. **Option A:** Let Visual Studio launch the app and start debugging + 1. Make sure that Metro is already running (i.e. `npx react-native start`) + 2. Make sure the desired *Configuration* (i.e. `Debug`) and *Platform* (i.e. `x64`) of your native app by setting the drop-downs in Visual Studio's top command bar + 3. In *Solution Explorer* right-click on your native app's project (i.e. `MyApp (Universal Windows)`) and select *Properties* + 1. For C++ RNW apps, open the *Configuration Properties > Debugging* page, set the *Debugger Type* to *Script Only*, then click *OK* + 2. For C# RNW apps, open the *Debug* tab, set the *Debugger type > Application process* to *Script*, then close the properties + 4. Click on *Debug* in the menu bar and select *Start Debugging* +4. **Option B:** Attach Visual Studio to the app that's already running + 1. Make sure that your native app and Metro is already running (i.e. using the [run-windows command](run-windows-cli.md)) + 2. Click on *Debug* in Visual Studio's menu bar and select *Attach to Process...* + 3. Find and select the native process for your app (not Metro) + 4. Make sure *Attach to:* is set to *Automatic: Script code* or *Script code* + > If *Attach to:* is set to something else, double check that *Script* is present in the *Type* column for your app's process. If it isn't, make sure you've enabled Direct Debugging in your app, and click the *Refresh* button. If *Script* is present under *Type* but not in *Attach to:*, click on the *Select...* button and try manually checking *Debug these code types: > Script*. + + 5. Click on the *Attach* button + +Once everything is running, you should be able to debug your RNW application. To set breakpoints, simply do so in your app's JS source files directly in Visual Studio. + +To see your app's JS source in Visual Studio, you can either: + +1. Open the files directly (via *Open > File...* in the *File* menu or by pressing `Ctrl+O`) OR +2. Looking for the files in the *Solution Explorer* sidebar under *`Solution 'MyApp'` > `Script Documents` > `file://...` > `script block` > `http://localhost:8081/...`* + +#### Using Visual Studio (Hermes) + +You can direct debug RNW apps using the Hermes JS engine with [Visual Studio](https://visualstudio.microsoft.com/) with the debugger from the *Node.js development* workload. + +1. Make sure you have Visual Studio installed with the *Node.js development* workload +2. Start Visual Studio without a solution file (*Continue without code*) +> **Important:** You should not have a solution file opened. There's a [known issue with trying to debug JS with your project's solution opened](https://github.com/microsoft/react-native-windows/issues/12842) that may be fixed, at which point this warning can be removed. + +3. **Option A:** Let Visual Studio launch the app and start debugging +> **Important:** Launching the app and starting direct debug with Hermes isn't supported in Visual Studio. + +4. **Option B:** Attach Visual Studio to the app that's already running + 1. Make sure that your native app and Metro is already running (i.e. using the [run-windows command](run-windows-cli.md)) + 2. Click on *Debug* in Visual Studio's menu bar and select *Attach to Process...* + 3. Make sure *Connection type:* is set to *JavaScript and TypeScript (Chrome DevTools/V8 Inspector)* + > If you don't see *JavaScript and TypeScript (Chrome DevTools/V8 Inspector)*, make sure you've installed the *Node.js development* workload for your version of Visual Studio. + + 4. Make sure *Connection target:* is set to `http://localhost:8081` + 5. Make sure *Attach to:* is set to *JavaScript and TypeScript* + 6. Find and select the *Hermes* from the process list + > If you don't see *Hermes* in the list, open a browser and navigate to `http://localhost:8081/json`. Copy the value of `webSocketDebuggerUrl` (i.e. something like `ws://[::1]:8081/inspector/debug?device=0&page=1`) and use that as the *Connection target* instead. + + 7. Click on the *Attach* button + +Once everything is running, you should be able to debug your RNW application. To set breakpoints, simply do so in your app's JS source files directly in Visual Studio. + +To see your app's JS source in Visual Studio, you can either: + +1. Open the files directly (via *Open > File...* in the *File* menu or by pressing `Ctrl+O`) OR +2. Looking for the files in the *Solution Explorer* sidebar under *`Solution 'MyApp'` > `Script Documents`* + + + +#### Using Visual Studio Code + +You can direct debug RNW apps using the Hermes JS engine with [VS Code](http://code.visualstudio.com/)'s built-in Node.js debugger. + +1. Make sure you have VS Code installed +2. Open your project's root folder in VS Code +3. Click on *Run* in VS Code's menu bar and select *Add Configuration...* +4. **Option A:** Let VS Code launch everything and start debugging +> **Important:** Launching everything and starting debugging isn't supported with VS Code's built-in Node.js debugger. + +5. **Option B:** Attach VS Code to Metro that's already running + 1. Depending on whether or not you already have a `launch.json` file, the drop-down will let you select *Node.js: Attach* (if it's available) or just *Node.js* + > If you don't see *Node.js*, try again without a code file opened in the editor. + + 2. A new (possibly incorrect) entry should appear in your `launch.json` file. The config will need to look like this (the `name` doesn't matter) to debug properly: + ```json + { + "name": "Attach", + "port": 8081, + "request": "attach", + "skipFiles": [ + "/**" + ], + "outFiles": [ + "${workspaceFolder}/**/*" + ], + "type": "node" + } + ``` + 3. Make sure that your native app and Metro is already running (i.e. using the [run-windows command](run-windows-cli.md)) + 4. Open the *Run and Debug* sidebar by clicking on the button in the sidebar or by pressing `Ctrl+Shift+D` + 5. Make sure the new config is selected at the top of the *Run and Debug* sidebar + 6. Click on the ▶️ button or press `F5` in VS Code + > Watch the *Call Stack* panel in the sidebar for *Attach: Remote Process* to indicate a successful debugger connection. Note, it may take VS Code a minute to scan your source before breakpoints will work properly. + +Once everything is running, you should be able to debug your RNW application. To set breakpoints, simply do so in your app's JS source files directly in VS Code. + +> Remember to save `launch.json` so you can reuse this debugging configuration in the future. + + + +#### Using Visual Studio Code with the React Native Tools + +You can direct debug RNW apps using the Hermes JS engine with [VS Code](http://code.visualstudio.com/) using the [React Native Tools](https://marketplace.visualstudio.com/items?itemName=msjsdiag.vscode-react-native) extension. + +1. Make sure you have VS Code and the React Native Tools extension installed +2. Open your project's root folder in VS Code +3. Click on *Run* in VS Code's menu bar and select *Add Configuration...* then *React Native* +> If you don't see *React Native*, try again without a code file opened in the editor. + +4. **Option A:** Let VS Code launch everything and start debugging + 1. Depending on whether or not you already have a `launch.json` file, the drop-down will either: + 1. Provide a list of debug configurations. Check the box for *Debug Windows Hermes -Experimental* and click *OK*. OR + 2. Guide you through a series of prompts. Select *Debug application*, *Windows*, *Application in direct mode(Hermes)*. + 2. A new (possibly incorrect) entry should appear in your `launch.json` file. The config will need to look like this (the `name` doesn't matter) to debug properly: + ```json + { + "name": "Debug Windows Hermes - Experimental", + "cwd": "${workspaceFolder}", + "type": "reactnativedirect", + "request": "launch", + "platform": "windows" + } + ``` + 3. Make sure that Metro and your native app are **not** already running + 4. Open the *Run and Debug* sidebar by clicking on the button in the sidebar or by pressing `Ctrl+Shift+D` + 5. Make sure the new config is selected at the top of the *Run and Debug* sidebar + 6. Click on the ▶️ button or press `F5` in VS Code + > Watch VS Code's *Debug Console* output for a successful debugger connection. This can be very slow, but VS Code should automatically launch Metro, establish the debugger connection, then launch your native app to download the bundle. + +5. **Option B:** Attach VS Code to Metro that's already running + 1. Depending on whether or not you already have a `launch.json` file, the drop-down will either: + 1. Provide a list of debug configurations. Check the box for *Attach to Hermes application* and click *OK*. OR + 2. Guide you through a series of prompts. Select *Attach to application*, *Application in direct mode(Hermes)*, *Hermes engine*, `localhost`, `8081`. + 2. A new (possibly incorrect) entry should appear in your `launch.json` file. The config will need to look like this (the `name` doesn't matter) to debug properly: + ```json + { + "name": "Attach to Hermes application - Experimental", + "cwd": "${workspaceFolder}", + "type": "reactnativedirect", + "request": "attach" + } + ``` + 3. Make sure that your native app and Metro is already running (i.e. using the [run-windows command](run-windows-cli.md)) + 4. Open the *Run and Debug* sidebar by clicking on the button in the sidebar or by pressing `Ctrl+Shift+D` + 5. Make sure the new config is selected at the top of the *Run and Debug* sidebar + 6. Click on the ▶️ button or press `F5` in VS Code + > Watch the *Call Stack* panel in the sidebar for *Attach: Remote Process* to indicate a successful debugger connection. + +Once everything is running, you should be able to debug your RNW application. To set breakpoints, simply do so in your app's JS source files directly in VS Code. + +> Remember to save `launch.json` so you can reuse this debugging configuration in the future. + + + +## Web Debugging + +*Web Debugging* (also referred to as *Remote JS Debugging*) was the original JS debugging solution for RN and RNW projects. + + +It works by running your app's JS code within the JS engine of an external process, usually a web browser such as Edge (or Chrome). You're then able to debug your app using the development tools of that external process, i.e. the browser's web development tools. + +> Web Debugging requires the Metro Packager, as Metro proxies the connection between your native Windows app and the remote JS engine. + +> **Important:** Web Debugging was officially marked as deprecated in RN 0.73 and will be removed in a later release. + +### Web Debugging Tool Support + +| JavaScript Engine | Edge Developer Tools | Visual Studio Code
w/ React Native Tools | +|:------------------|:-:|:-:| +| Hermes (Default) | ✅ | ✅ | +| Chakra | ✅ | ✅ | + +> **Important:** As your code is run in the remote JS engine, the app's embedded engine is not used. This can cause your released app to behave differently when it *is* using the embedded engine. See [Web vs. Direct Debugging](#web-vs-direct-debugging) for details\. + +### Step 1: Enable Web Debugging + + + +Web Debugging can be enabled by setting `UseWebDebugger` property of your app's `InstanceSettings` during startup. + + + + + +#### Modifying your C# RNW app + + +1. You'll want to edit your `App`'s constructor in `App.xaml.cs` with: + +```csharp +InstanceSettings.UseWebDebugger = true; +InstanceSettings.UseDirectDebugger = false; +``` + + + +#### Modifying your C++ RNW app + + +1. You'll want to edit your `App`'s constructor in `App.cpp` with: + +```c++ +InstanceSettings().UseWebDebugger(true); +InstanceSettings().UseDirectDebugger(false); +``` + + + +2. Then simply re-build and launch your RNW app as usual. + +> Unless otherwise specified, for a new RNW app, `UseWebDebugger` defaults to `false`. + +### Step 2: Connect a debugger + +The next step is to connect to Metro with your chosen debugger / development tools. + +> This must happen before the native app attempts to download the JS bundle from Metro. If a debugger is not already attached, Metro will automatically attempt to set up the Edge Developer Tools. + + + + + +#### Using the Edge Developer Tools + +You can web debug within Edge by using the [Edge Developer Tools](https://learn.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium/). + +> If you use Chrome, the process is similar for using the [Chrome Developer Tools](https://developer.chrome.com/docs/devtools/). + +1. Launch your RNW app (with Web Debugging enabled and Metro running) +2. In Edge, open the URL http://localhost:8081/debugger-ui/ +> Metro may have already opened it, look for a *React Native Debugger* tab. + +3. Press `Ctrl+Shift+J` on the page to launch the Developer Tools + +You should now be able to debug your RNW application. To set breakpoints you'll find your app's JS source files in the *Sources* tab under *`debuggerWorker.js` > `localhost:8081` > `src/ui`*. + + + +#### Using Visual Studio Code with the React Native Tools + +You can web debug within [VS Code](http://code.visualstudio.com/) by using the [React Native Tools](https://marketplace.visualstudio.com/items?itemName=msjsdiag.vscode-react-native) extension. + +> **Important**: You will not be able to connect VS Code to Metro if the Edge Developer Tools (or another debugger) is already connected. So double check you don't have any previous *React Native Debugger* browser tabs open before running these steps. + +1. Make sure you have VS Code and the React Native Tools extension installed +2. Open your project's root folder in VS Code +3. Click on *Run* in VS Code's menu bar and select *Add Configuration...* then *React Native* +> If you don't see *React Native*, try again without a code file opened in the editor. + +4. **Option A:** Let VS Code launch everything and start debugging + 1. Depending on whether or not you already have a `launch.json` file, the drop-down will either: + 1. Provide a list of debug configurations. Check the box for *Debug Windows* and click *OK*. OR + 2. Guide you through a series of prompts. Select *Debug application*, *Windows*, *Classic application*. + 2. A new (possibly incorrect) entry should appear in your `launch.json` file. The config will need to look like this (the `name` doesn't matter) to debug properly: + ```json + { + "name": "Debug Windows", + "cwd": "${workspaceFolder}", + "type": "reactnative", + "request": "launch", + "platform": "windows" + } + ``` + 3. Make sure that Metro, your native app, and/or any browser Developer Tools are **not** already running + 4. Make sure the new config is selected at the top of the *Run and Debug* sidebar + 5. Click on the ▶️ button or press `F5` in VS Code + > Watch VS Code's *Debug Console* output for a successful debugger connection. This can be very slow, but VS Code should automatically launch Metro, establish the debugger connection, then launch your native app to download the bundle. + +5. **Option B:** Attach VS Code to Metro that's already running + 1. Depending on whether or not you already have a `launch.json` file, the drop-down will either: + 1. Provide a list of debug configurations. Check the box for *Attach to packager* and click *OK*. OR + 2. Guide you through a series of prompts. Select *Attach to application*, *Classic application*, `localhost`, `8081`. + 2. A new (possibly incorrect) entry should appear in your `launch.json` file. The config will need to look like this (the `name` doesn't matter) to debug properly: + ```json + { + "name": "Attach to packager", + "cwd": "${workspaceFolder}", + "type": "reactnative", + "request": "attach" + } + ``` + 3. Make sure that only Metro is already running (i.e. `npx react-native start`) + 4. Make sure the new config is selected at the top of the *Run and Debug* sidebar + 5. Click on the ▶️ button or press `F5` in VS Code + > Watch VS Code's *Debug Console* output for a successful debugger connection. + + 6. Manually launch your native app + +Once everything is running, you should be able to debug your RNW application. To set breakpoints, simply do so in your app's JS source files directly in VS Code. + +> Remember to save `launch.json` so you can reuse this debugging configuration in the future. + +> *Important:* If you're having difficulty getting VS Code to connect with Web Debugging, double check you're not running any part of RNW (watch out for rogue `node.exe` processes) before starting the steps above. + + + +## Web vs. Direct Debugging + +As mentioned above, RNW supports both Web and Direct Debugging, and it's worth knowing when to use each. + +Web Debugging is the older, more well-established of the two debugging solutions. It relies on the powerful in-browser debugging tools already familiar to web developers. This reinforces RN's purpose of enabling web developers to build native apps with web technologies. + +However, Web Debugging is not without its limitations. The primary problem is that JS can behave slightly differently when running in different JS engines. As such, by developing (and testing) your app while using a browser to run the JS, you might miss bugs or other issues that only manifest when running your app normally with the embedded JS engine. + +This requires developers to double check all of their app's functionality in the release build, or risk situations where customers find bugs in production that aren't reproducible when using Web Debugging. + +Furthermore, some parts of RN, such as synchronous calls to native module methods, only work when running on the embedded JS engine. Such native methods won't work when using Web Debugging. + +With Direct Debugging, you're debugging your JS code in the same engine you ship with your final app. This removes that class of bugs caused by using a different engine while in development. + +However, Direct Debugging has its own limitations too. It is newer and therefore more likely to have setup and stability issues. Furthermore, the JS debugger you want to use might not support the JS engine you want your app to use. + +It is important to note, that while Web Debugging may be a sufficient for your needs now, both the RN and RNW teams are focusing future investment into the Direct Debugging experience. + +## Other Tools + +Here are some other tools you find useful while debugging your RNW apps. + +### React Developer Tools + +The [React Developer Tools](https://beta.reactjs.org/learn/react-developer-tools) can be used to inspect your app's React component hierarchy and perform performance profiling. It works in conjunction with either Web or Direct Debugging. + +1. Launch your RNW app (with Metro running) +2. Run `npx react-devtools` from the command line +3. With your RNW app running, press `Ctrl+Shift+D` to invoke the Developer Menu + +The React Developer Tools should detect the Developer Menu opening and automatically attach to your app. diff --git a/website/versioned_docs/version-0.75/getting-started.md b/website/versioned_docs/version-0.75/getting-started.md new file mode 100644 index 000000000..8927da663 --- /dev/null +++ b/website/versioned_docs/version-0.75/getting-started.md @@ -0,0 +1,139 @@ +--- +id: version-0.75-getting-started +title: Get Started with Windows +original_id: getting-started +--- + +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](rnw-dependencies.md). + +For information around how to set up React Native, see the [React Native Getting Started Guide](https://reactnative.dev/docs/getting-started). + +## Create a new React Native project + +Remember to call `@react-native-community/cli init` from the place you want your project directory to live. + + + + + + + + + + +```bat +npx --yes @react-native-community/cli@next init --version "latest" +``` + +### Navigate into this newly created directory + +React Native will have created your project in a new sub-directory, which you must enter before continuing. + +```bat +cd +``` + +### Add React Native Windows to your project's dependencies + + + + + + + + + + + +```bat +yarn add react-native-windows@latest +``` + + + +```bat +npm install --save react-native-windows@latest +``` + + + +### Initialize the React Native Windows native code and projects + +Lastly, initialize the React Native for Windows application with the [init-windows command](init-windows-cli.md): + +```bat +npx react-native init-windows --overwrite +``` + +> **Note:** RNW templates contain a customized `metro.config.js` file, which is meant to merge cleanly into the default config provided by the standard React Native project template. If you are starting a new app, overwriting `metro.config.js` should have no impact. However, if you are adding Windows to an existing app with an already modified `metro.config.js` file, please make sure to back up and re-apply your modifications after adding RNW. + +> **Note:** Previous versions of the RNW Getting Started steps recommend the use of the `react-native-windows-init` command, which is being phased out. For documentation of that command, see: [React Native Windows Init CLI](https://microsoft.github.io/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](rnw-dependencies.md) to build a Windows app as well. + +- Without Using Visual Studio + + In your React Native Windows project directory, run the [run-windows command](run-windows-cli.md): + + ```bat + npx react-native run-windows + ``` + + A new Command Prompt window will open with the React packager as well as your React Native for Windows app. This step may take a while during first run since it involves building the entire project and all dependencies. You can now start developing! :tada: + +- Using Visual Studio + + - From the root of the project directory, run the [autolink-windows command](autolink-windows-cli.md), which will automatically link your app's dependencies: + ```bat + npx react-native autolink-windows + ``` + - Open the solution file in the application folder in Visual Studio (e.g., `AwesomeProject/windows/AwesomeProject.sln` if you used `AwesomeProject` as ``) + - Select the `Debug` configuration and the `x64` platform from the combo box controls to the left of the `Run` button and underneath the `Team` and `Tools` menu item. + - Run `yarn start` (or `npm start`) from your project directory, and wait for the React Native packager to report success. + - Click the `Run` button to the right of the platform combo box control in VS, or select the `Debug`->`Start without Debugging` menu item. You now see your new app and Chrome should have loaded `http://localhost:8081/debugger-ui/` in a new tab. Press `F12` or `Ctrl+Shift+I` in Chrome to open its Developer Tools. :tada: + +- With VS Code + - Open your applications folder in VS Code. + - Install the [React Native Tools](https://marketplace.visualstudio.com/items?itemName=msjsdiag.vscode-react-native) plugin for VS Code. + - Create a new file in the applications root directory, `.vscode/launch.json` and paste the following configuration: + ```json + { + "version": "0.2.0", + "configurations": [ + { + "name": "Debug Windows", + "cwd": "${workspaceFolder}", + "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 + +See [Native Modules and React Native Windows](native-modules.md). + +## 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`](https://github.com/microsoft/react-native-windows/blob/6b415659aa017dbc41e3f28e817fb768a8e80435/vnext/template/cpp-app/src/App.cpp#L30) or [`App.xaml.cs`](https://github.com/microsoft/react-native-windows/blob/6b415659aa017dbc41e3f28e817fb768a8e80435/vnext/template/cs-app/src/App.xaml.cs#L20) to get the same behavior in the Debug configuration. + +See also this article for additional details: https://techcommunity.microsoft.com/t5/windows-dev-appconsult/getting-started-with-react-native-for-windows/ba-p/912093# + + + diff --git a/website/versioned_docs/version-0.75/hermes.md b/website/versioned_docs/version-0.75/hermes.md new file mode 100644 index 000000000..36448cff2 --- /dev/null +++ b/website/versioned_docs/version-0.75/hermes.md @@ -0,0 +1,120 @@ +--- +id: version-0.75-hermes +title: Hermes on Windows + macOS +original_id: hermes +--- + +# Hermes + +The [Hermes](https://hermesengine.dev/) engine is an open source JavaScript engine created by Facebook to optimize building and running React Native applications. + +To learn more about what it is and how to use it, check out the [React Native](https://reactnative.dev/docs/hermes#docsNav) documentation for it. + +## Hermes on Windows: + +Hermes is supported on Windows, generally providing better performance characteristics than the default Chakra engine. + +### Enabling Hermes for new projects + +Hermes is enabled by default for React Native Windows projects. + +### Using Hermes in an existing project + +Set the `UseHermes` property to `true` in the `ExperimentalFeatures.props` file in your project's `windows` directory: + +```xml + + ... + true + +``` + +### Disabling Hermes + +To revert back to using Chakra, set the `UseHermes` property to `false` in the `ExperimentalFeatures.props` file in your project's `windows` directory: + +```xml + + ... + false + +``` + +### Known limitations + +- Hermes dll is not signed by Microsoft. + +## Hermes on macOS + +Hermes is available on React Native for macOS, provided you are using version 0.62 or higher. +To learn how to upgrade to the latest version, check out the **Upgrading** section of the [macOS Getting Started guide](rnm-getting-started.md). + +After you have upgraded to the latest version of React Native for macOS, install and add the following: + +1. Install the npm package `yarn add 'hermes-engine-darwin@^0.4.3'` +2. Add (or uncomment) the following pod dependencies to your macOS target in your `Podfile`:
+ +``` +pod 'React-Core/Hermes', :path => '../node_modules/react-native-macos/' +pod 'hermes', :path => '../node_modules/hermes-engine-darwin' +pod 'libevent', :podspec => '../node_modules/react-native-macos/third-party-podspecs/libevent.podspec' +``` + +3. Run `pod install` + +> Be sure to set your target's deployment target to at least 10.14 before running `pod install` + +## Hermes Inspector + +*React Native for Windows* with *Hermes engine* supports direct JavaScript runtime inspection using tools such as Chrome or [Edge `devtools`](https://docs.microsoft.com/microsoft-edge/devtools-guide-chromium/), [`VSCode` debugger](https://code.visualstudio.com/Docs/editor/debugging), [Flipper](https://fbflipper.com/) etc. by implementing an in-process Chrome Debug Protocol server. +Please note that it is fundamentally different from "Remote JS Debugging", which loads the JavaScript bundle into a remote Chrome browser session with duplex communication over IPC channels. + +We share the implementation (code and design) with other platforms wherever possible. All the external endpoints, APIs and protocols should be identical to *React Native* environments on other platforms. +Hence, we expect most tooling available on other platforms to just work on Windows. But, as of now, we have tested only with Chrome and Edge `devtools`. + +### Steps to enable direct debugging + +1. Initialize React Native Host, + - Turn on `DeveloperSupport` + - Turn on `FastRefresh` + - Turn off `WebDebugger` + - Turn on `Direct Debugging` +2. Ensure Dev-Server is running +3. Start the application + +After the app has booted, + +4. Navigate to `edge://inspect` in Edge browser or `chrome://inspect` in Chrome browser +5. Enable **Discover network targets** and **configure** the target discovery settings to include `localhost:8081` (or wherever the metro server is running) +6. Within a few seconds "Hermes React Native" should appear on the page as a remote target +7. Click on the **inspect** link to launch the `devtools` page +8. Click `Ctrl+P` to open source files and set break points +9. Alternatively, you can insert `debugger` statements in source code to break on specific locations + +In order to break on locations during boot, you can either + +- Add statements into the boot sequence to pause the runtime waiting for debugger to connect. +```js +debugger; +``` +- Set a break point and refresh the bundle through the Dev Server. The runtime will wait for debugger to attach. + + +### Steps to enable heap profiling + +Follow steps 1-7 from above, and then +1. Click on the "Memory" tab in the inspector +2. Heap snapshots and instrumented allocations should be working. + +### Enable debugging/profiling on release builds + +We keep the inspector turned off on release builds by default. If you want to debug or profile release builds, set the MSBuild property `EnableHermesInspectorInReleaseFlavor` to `'true'` when building the platform with the [run-windows command](run-windows-cli.md), i.e.: + +```bash +npx react-native run-windows --msbuildprops EnableHermesInspectorInReleaseFlavor=true +``` + +### Known Issues + +1. CPU Sampling profiler currently doesn't work. + diff --git a/website/versioned_docs/version-0.75/init-windows-cli.md b/website/versioned_docs/version-0.75/init-windows-cli.md new file mode 100644 index 000000000..8f05d20b1 --- /dev/null +++ b/website/versioned_docs/version-0.75/init-windows-cli.md @@ -0,0 +1,50 @@ +--- +id: version-0.75-init-windows-cli +title: react-native init-windows +original_id: init-windows-cli +--- + +This guide will give you more information on the `init-windows` command of the React Native Windows CLI. + +## `init-windows` + +The `init-windows` CLI command is used to initialize a new React Native for Windows project inside an existing React Native project. + +### Usage +Initializes a new RNW project from a given template. + +```bat +npx react-native init-windows +``` +### Options + +Here are the options that `react-native init-windows` takes: +| Option | Input Type | Description | +|-----------------------|------------|--------------------------------------------------| +| `--logging` | boolean | Verbose output logging | +| `--template` | string | Specify the template to use | +| `--name` | string | The native project name. Defaults to the name property in `app.json` or `package.json` | +| `--namespace` | string | The native project namespace, expressed using dots as separators, i.e. `Level1.Level2.Level3`. Defaults to the same as name | +| `--overwrite` | boolean | Overwrite any existing files without prompting | +| `--no-telemetry` | boolean | Disables sending telemetry that allows analysis of usage and failures of the react-native-windows CLI | +| `-h`, `--help` | boolean | Display help for command | + +### Templates + +The following templates are available for use with `init-windows` by replacing `--template XYZ`, where `XYZ` can be: + +| Template | Name | +|:-:|:--| +| `cpp-app` | React Native Windows Application (New Arch, C++, Win32, Hermes) | +| `cpp-lib` | React Native Windows Turbo Module (New Arch, C++) | +| `old/uwp-cpp-app` | React Native Windows Application (Old Arch, UWP, C++) | +| `old/uwp-cpp-lib` | React Native Windows Library (Old Arch, UWP, C++) | +| `old/uwp-cs-app` | React Native Windows Application (Old Arch, UWP, C#) | +| `old/uwp-cs-lib` | React Native Windows Library (Old Arch, UWP, C#) | + +This sends telemetry to Microsoft by default. You can prevent the telemetry from being sent by using the `--no-telemetry` command line option. See below for more details. + +The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices. + +This data collection notice only applies to the process of running the react-native-windows CLI commands. + \ No newline at end of file diff --git a/website/versioned_docs/version-0.75/native-api/HttpSettings-api-windows.md b/website/versioned_docs/version-0.75/native-api/HttpSettings-api-windows.md new file mode 100644 index 000000000..9ab5fe906 --- /dev/null +++ b/website/versioned_docs/version-0.75/native-api/HttpSettings-api-windows.md @@ -0,0 +1,23 @@ +--- +id: version-0.75-HttpSettings +title: HttpSettings +original_id: HttpSettings +--- + +Kind: `class` + + + +Provides settings for Http functionality. + + + +## Methods +### SetDefaultUserAgent +`static` void **`SetDefaultUserAgent`**([`ReactInstanceSettings`](ReactInstanceSettings) settings, string userAgent) + +Configures the react instance to use a user-agent header by default on http requests. + + + + diff --git a/website/versioned_docs/version-0.75/native-api/ReactInstanceSettings-api-windows.md b/website/versioned_docs/version-0.75/native-api/ReactInstanceSettings-api-windows.md new file mode 100644 index 000000000..3079e70d6 --- /dev/null +++ b/website/versioned_docs/version-0.75/native-api/ReactInstanceSettings-api-windows.md @@ -0,0 +1,231 @@ +--- +id: version-0.75-ReactInstanceSettings +title: ReactInstanceSettings +original_id: ReactInstanceSettings +--- + +Kind: `class` + + + +Provides settings to create a React instance. + +## Properties +### BundleAppId + string `BundleAppId` + +The name of the app passed to the packager server via the 'app' query parameter. This is useful when bundling multiple applications from the same packager instance. If no value is set, the parameter will not be passed. + +### BundleRootPath + string `BundleRootPath` + +**Default value**: `ms-appx:///Bundle/` + +Base path used for the location of the bundle. +This can be an `ms-appx://` or `ms-appdata://` URI (if the app is UWP or packaged using MSIX), a filesystem path, or a URI pointing at an embedded resource. +Examples: + +- `ms-appx:///Bundle` - locates the bundle in the MSIX package. See [URI schemes](https://docs.microsoft.com/windows/uwp/app-resources/uri-schemes) for other UWP/MSIX valid URI formats. +- `C:\\foo\\bar` - locates the bundle in the local filesystem. Note [UWP app file access permissions](https://docs.microsoft.com/windows/uwp/files/file-access-permissions). +- `resource://moduleName` - locates the bundle as an embedded RCDATA resource in moduleName. Specify the resource ID in [`JavaScriptBundleFile`](#javascriptbundlefile). +- `resource://` - locates the bundle as an embedded RCDATA resource in the running process's module. Specify the resource ID in [`JavaScriptBundleFile`](#javascriptbundlefile). + + +### ByteCodeFileUri + string `ByteCodeFileUri` + +Set this to a location the application has write access to in order for bytecode to be successfully cached. See [`EnableByteCodeCaching`](#enablebytecodecaching). +**Note that currently the byte code generation is not implemented for UWP applications.** + +### DebugBundlePath + string `DebugBundlePath` + +When loading from a bundle server (such as metro), this is the path that will be requested from the server. If this is not provided, the value of [`JavaScriptBundleFile`](#javascriptbundlefile) is used. + +### DebuggerBreakOnNextLine + bool `DebuggerBreakOnNextLine` + +For direct debugging, controls whether to break on the next line of JavaScript that is executed. +This can help debug issues hit early in the JavaScript bundle load. +***Note: this is not supported with the Chakra JS engine which is the currently used JavaScript engine. As a workaround you could add the `debugger` keyword in the beginning of the bundle.*** + +### DebuggerPort + uint16_t `DebuggerPort` + +**Default value**: `9229` + +When [`UseDirectDebugger`](#usedirectdebugger) is enabled, this controls the port that the JavaScript engine debugger will run on. + +### DebuggerRuntimeName + string `DebuggerRuntimeName` + +Name to associate with the JavaScript runtime when debugging. +This name will show up in the list of JavaScript runtimes to attach to in edge://inspect or other debuggers + +### EnableByteCodeCaching + bool `EnableByteCodeCaching` + +**Default value**: `false` + +For JS engines that support bytecode generation, this controls if bytecode should be generated when a JavaScript bundle is first loaded. +Subsequent runs of the application should be faster as the JavaScript will be loaded from bytecode instead of the raw JavaScript. +[`ByteCodeFileUri`](#bytecodefileuri) must be set to a location the application has write access to in order for the bytecode to be successfully cached. +**Note that currently the byte code generation is not implemented for UWP applications.** + +### EnableDefaultCrashHandler + bool `EnableDefaultCrashHandler` + +**Default value**: `false` + +Enables the default unhandled exception handler that logs additional information into a text file for [Windows Error Reporting](https://docs.microsoft.com/windows/win32/wer/windows-error-reporting). + +### EnableDeveloperMenu + bool `EnableDeveloperMenu` + +> **Deprecated**: This property has been replaced by [`UseDeveloperSupport`](#usedevelopersupport). In version 0.63 both properties will do the same thing. It will be removed in a future version. + +This controls whether various developer experience features are available for this instance. In particular the developer menu, and the default `RedBox` experience. + +### EnableJITCompilation + bool `EnableJITCompilation` + +**Default value**: `true` + +Flag controlling whether the JavaScript engine uses JIT compilation. + +### JSIEngineOverride + [`JSIEngine`](JSIEngine) `JSIEngineOverride` + +**Default value**: `JSIEngine.Chakra` + +The [`JSIEngine`](JSIEngine) override to be used with the React instance. +In order for the override to work, Microsoft.ReactNative must be compiled with support of that engine. This override will be ignored when [`UseWebDebugger`](#usewebdebugger) is set to true, since the browser must use its own engine to debug correctly. + +### JavaScriptBundleFile + string `JavaScriptBundleFile` + +**Default value**: `index.windows` + +The name of the JavaScript bundle file to load. This should be a relative path from [`BundleRootPath`](#bundlerootpath). The `.bundle` extension will be appended to the end, when looking for the bundle file. +If using an embedded RCDATA resource, this identifies the resource ID that stores the bundle. See [`BundleRootPath`](#bundlerootpath). + +### NativeLogger + [`LogHandler`](LogHandler) `NativeLogger` + +Function that will be hooked into the JavaScript instance as global.nativeLoggingHook. This allows native hooks for JavaScript's console implementation. If this is not set then logs will print output to the native debug output in debug builds, and no-op in release builds. + +### Notifications +`readonly` [`IReactNotificationService`](IReactNotificationService) `Notifications` + +Gets a [`IReactNotificationService`](IReactNotificationService) to send notifications between components and the application. +Use [`IReactContext.Notifications`](IReactContext#notifications) to access this [`IReactNotificationService`](IReactNotificationService) from native components or view managers. + +### PackageProviders +`readonly` [`IVector`](https://docs.microsoft.com/uwp/api/Windows.Foundation.Collections.IVector-1)<[`IReactPackageProvider`](IReactPackageProvider)> `PackageProviders` + +Gets a list of [`IReactPackageProvider`](IReactPackageProvider). +Add an implementation of [`IReactPackageProvider`](IReactPackageProvider) to this list to define additional native modules and custom view managers to be included in the React instance. +Auto-linking automatically adds [`IReactPackageProvider`](IReactPackageProvider) to the application's [`PackageProviders`](#packageproviders). + +### Properties +`readonly` [`IReactPropertyBag`](IReactPropertyBag) `Properties` + +Gets a [`IReactPropertyBag`](IReactPropertyBag) to share values between components and the application. +Use [`IReactContext.Properties`](IReactContext#properties-1) to access this [`IReactPropertyBag`](IReactPropertyBag) from native components and view managers. + +### RedBoxHandler + [`IRedBoxHandler`](IRedBoxHandler) `RedBoxHandler` + +Provides an extension point to allow custom error handling within the react instance. See [`IRedBoxHandler`](IRedBoxHandler) for more information. + +### RequestDevBundle + bool `RequestDevBundle` + +When querying the bundle server for a bundle, should it request the dev bundle or release bundle. + +### RequestInlineSourceMap + bool `RequestInlineSourceMap` + +**Default value**: `true` + +When using [`UseFastRefresh`](#usefastrefresh), [`UseLiveReload`](#uselivereload), or [`UseWebDebugger`](#usewebdebugger) this controls whether the bundler should include inline source maps.If set, the bundler will include the source maps inline (this will improve debugging experience, but for very large bundles it could have a significant performance hit) + +### SourceBundleHost + string `SourceBundleHost` + +**Default value**: `localhost` + +When using [`UseFastRefresh`](#usefastrefresh), [`UseLiveReload`](#uselivereload), or [`UseWebDebugger`](#usewebdebugger) this is the server hostname that will be used to load the bundle from. + +### SourceBundlePort + uint16_t `SourceBundlePort` + +**Default value**: `8081` + +When using [`UseFastRefresh`](#usefastrefresh), [`UseLiveReload`](#uselivereload), or [`UseWebDebugger`](#usewebdebugger) this is the server port that will be used to load the bundle from. + +### UIDispatcher + [`IReactDispatcher`](IReactDispatcher) `UIDispatcher` + +Control the main UI dispatcher to be used by the React instance. If the [`ReactInstanceSettings`](ReactInstanceSettings) object is initially created on a UI thread, then this will default to that thread. The value provided here will be available to native modules and view managers using [`IReactContext.UIDispatcher`](IReactContext#uidispatcher) + +### UseDeveloperSupport + bool `UseDeveloperSupport` + +This controls whether various developer experience features are available for this instance. In particular, it enables the developer menu, the default `RedBox` and `LogBox` experience. + +### UseDirectDebugger + bool `UseDirectDebugger` + +Enables debugging in the JavaScript engine (if supported). +For Chakra this enables debugging of the JS runtime directly within the app using Visual Studio -> Attach to process (Script) + +### UseFastRefresh + bool `UseFastRefresh` + +Controls whether the instance triggers the hot module reload logic when it first loads the instance. +Most edits should be visible within a second or two without the instance having to reload. +Non-compatible changes still cause full reloads. +See [Fast Refresh](https://reactnative.dev/docs/fast-refresh) for more information on Fast Refresh. + +### UseLiveReload + bool `UseLiveReload` + +> **Deprecated**: For general use this has been replaced by [`UseFastRefresh`](#usefastrefresh). + +Enables live reload to load the source bundle from the React Native packager. +When the file is saved, the packager will trigger reloading. + + +### UseWebDebugger + bool `UseWebDebugger` + +> **Deprecated**: Debugging should be done using DirectDebugging rather than WebDebugger. Web debugging changes the app behavior and will be removed in a future version. + +Controls whether the instance JavaScript runs in a remote environment such as within a browser. +By default, this is using a browser navigated to http://localhost:8081/debugger-ui served by Metro/Haul. +Debugging will start as soon as the react native instance is loaded. + + +## Constructors +### ReactInstanceSettings + **`ReactInstanceSettings`**() + + + + + +## Events +### `InstanceCreated` +Type: [`InstanceCreatedEventArgs`](InstanceCreatedEventArgs) +### `InstanceDestroyed` +Type: [`InstanceDestroyedEventArgs`](InstanceDestroyedEventArgs) +### `InstanceLoaded` +Type: [`InstanceLoadedEventArgs`](InstanceLoadedEventArgs) + + +## Referenced by +- [`HttpSettings`](HttpSettings) +- [`QuirkSettings`](QuirkSettings) +- [`ReactApplication`](ReactApplication) +- [`ReactNativeHost`](ReactNativeHost) diff --git a/website/versioned_docs/version-0.75/native-api/index-api-windows.md b/website/versioned_docs/version-0.75/native-api/index-api-windows.md new file mode 100644 index 000000000..afa7c5e64 --- /dev/null +++ b/website/versioned_docs/version-0.75/native-api/index-api-windows.md @@ -0,0 +1,130 @@ +--- +id: version-0.75-Native-API-Reference +title: namespace Microsoft.ReactNative +sidebar_label: Full reference +: +original_id: Native-API-Reference +--- + +## Enums +- [`AccessibilityRoles`](AccessibilityRoles) +- [`AccessibilityStateCheckedValue`](AccessibilityStateCheckedValue) +- [`AccessibilityStates`](AccessibilityStates) +- [`AccessibilityValue`](AccessibilityValue) +- [`AriaRole`](AriaRole) +- [`BackNavigationHandlerKind`](BackNavigationHandlerKind) +- [`CanvasComposite`](CanvasComposite) +- [`CanvasEdgeBehavior`](CanvasEdgeBehavior) +- [`EffectBorderMode`](EffectBorderMode) +- [`EffectOptimization`](EffectOptimization) +- [`JSIEngine`](JSIEngine) +- [`JSValueType`](JSValueType) +- [`JsiErrorType`](JsiErrorType) +- [`JsiValueKind`](JsiValueKind) +- [`LoadingState`](LoadingState) +- [`LogLevel`](LogLevel) +- [`MethodReturnType`](MethodReturnType) +- [`PointerEventKind`](PointerEventKind) +- [`RedBoxErrorType`](RedBoxErrorType) +- [`ViewManagerPropertyType`](ViewManagerPropertyType) +## Interfaces +- [`IJSValueReader`](IJSValueReader) +- [`IJSValueWriter`](IJSValueWriter) +- [`IJsiByteBuffer`](IJsiByteBuffer) +- [`IJsiHostObject`](IJsiHostObject) +- [`IReactContext`](IReactContext) +- [`IReactDispatcher`](IReactDispatcher) +- [`IReactModuleBuilder`](IReactModuleBuilder) +- [`IReactNonAbiValue`](IReactNonAbiValue) +- [`IReactNotificationArgs`](IReactNotificationArgs) +- [`IReactNotificationService`](IReactNotificationService) +- [`IReactNotificationSubscription`](IReactNotificationSubscription) +- [`IReactPackageBuilder`](IReactPackageBuilder) +- [`IReactPackageProvider`](IReactPackageProvider) +- [`IReactPropertyBag`](IReactPropertyBag) +- [`IReactPropertyName`](IReactPropertyName) +- [`IReactPropertyNamespace`](IReactPropertyNamespace) +- [`IReactSettingsSnapshot`](IReactSettingsSnapshot) +- [`IReactViewHost`](IReactViewHost) +- [`IReactViewInstance`](IReactViewInstance) +- [`IRedBoxErrorFrameInfo`](IRedBoxErrorFrameInfo) +- [`IRedBoxErrorInfo`](IRedBoxErrorInfo) +- [`IRedBoxHandler`](IRedBoxHandler) +- [`ITimer`](ITimer) +- [`IViewManager`](IViewManager) +- [`IViewManagerCreateWithProperties`](IViewManagerCreateWithProperties) +- [`IViewManagerRequiresNativeLayout`](IViewManagerRequiresNativeLayout) +- [`IViewManagerWithChildren`](IViewManagerWithChildren) +- [`IViewManagerWithCommands`](IViewManagerWithCommands) +- [`IViewManagerWithDropViewInstance`](IViewManagerWithDropViewInstance) +- [`IViewManagerWithExportedEventTypeConstants`](IViewManagerWithExportedEventTypeConstants) +- [`IViewManagerWithExportedViewConstants`](IViewManagerWithExportedViewConstants) +- [`IViewManagerWithNativeProperties`](IViewManagerWithNativeProperties) +- [`IViewManagerWithOnLayout`](IViewManagerWithOnLayout) +- [`IViewManagerWithPointerEvents`](IViewManagerWithPointerEvents) +- [`IViewManagerWithReactContext`](IViewManagerWithReactContext) +## Structs +- [`AccessibilityAction`](AccessibilityAction) +- [`DesktopWindowMessage`](DesktopWindowMessage) +- [`JsiBigIntRef`](JsiBigIntRef) +- [`JsiObjectRef`](JsiObjectRef) +- [`JsiPropertyIdRef`](JsiPropertyIdRef) +- [`JsiScopeState`](JsiScopeState) +- [`JsiStringRef`](JsiStringRef) +- [`JsiSymbolRef`](JsiSymbolRef) +- [`JsiValueRef`](JsiValueRef) +- [`JsiWeakObjectRef`](JsiWeakObjectRef) +## Classes +- [`BorderEffect`](BorderEffect) +- [`ColorSourceEffect`](ColorSourceEffect) +- [`CompositeStepEffect`](CompositeStepEffect) +- [`DevMenuControl`](DevMenuControl) +- [`DynamicAutomationPeer`](DynamicAutomationPeer) +- [`DynamicAutomationProperties`](DynamicAutomationProperties) +- [`DynamicValueProvider`](DynamicValueProvider) +- [`GaussianBlurEffect`](GaussianBlurEffect) +- [`HttpSettings`](HttpSettings) +- [`InstanceCreatedEventArgs`](InstanceCreatedEventArgs) +- [`InstanceDestroyedEventArgs`](InstanceDestroyedEventArgs) +- [`InstanceLoadedEventArgs`](InstanceLoadedEventArgs) +- [`JsiError`](JsiError) +- [`JsiPreparedJavaScript`](JsiPreparedJavaScript) +- [`JsiRuntime`](JsiRuntime) +- [`LayoutService`](LayoutService) +- [`QuirkSettings`](QuirkSettings) +- [`ReactApplication`](ReactApplication) +- [`ReactCoreInjection`](ReactCoreInjection) +- [`ReactDispatcherHelper`](ReactDispatcherHelper) +- [`ReactInstanceSettings`](ReactInstanceSettings) +- [`ReactNativeHost`](ReactNativeHost) +- [`ReactNotificationServiceHelper`](ReactNotificationServiceHelper) +- [`ReactPointerEventArgs`](ReactPointerEventArgs) +- [`ReactPropertyBagHelper`](ReactPropertyBagHelper) +- [`ReactRootView`](ReactRootView) +- [`ReactViewOptions`](ReactViewOptions) +- [`RedBoxHelper`](RedBoxHelper) +- [`Timer`](Timer) +- [`ViewControl`](ViewControl) +- [`ViewPanel`](ViewPanel) +- [`XamlHelper`](XamlHelper) +- [`XamlMetaDataProvider`](XamlMetaDataProvider) +- [`XamlUIService`](XamlUIService) +## Delegates +- [`AccessibilityActionEventHandler`](AccessibilityActionEventHandler) +- [`AccessibilityInvokeEventHandler`](AccessibilityInvokeEventHandler) +- [`ConstantProviderDelegate`](ConstantProviderDelegate) +- [`InitializerDelegate`](InitializerDelegate) +- [`JSValueArgWriter`](JSValueArgWriter) +- [`JsiByteArrayUser`](JsiByteArrayUser) +- [`JsiHostFunction`](JsiHostFunction) +- [`LogHandler`](LogHandler) +- [`MethodDelegate`](MethodDelegate) +- [`MethodResultCallback`](MethodResultCallback) +- [`ReactCreatePropertyValue`](ReactCreatePropertyValue) +- [`ReactDispatcherCallback`](ReactDispatcherCallback) +- [`ReactModuleProvider`](ReactModuleProvider) +- [`ReactNotificationHandler`](ReactNotificationHandler) +- [`ReactViewManagerProvider`](ReactViewManagerProvider) +- [`SyncMethodDelegate`](SyncMethodDelegate) +- [`TimerFactory`](TimerFactory) +- [`UIBatchCompleteCallback`](UIBatchCompleteCallback) diff --git a/website/versioned_docs/version-0.75/native-code.md b/website/versioned_docs/version-0.75/native-code.md new file mode 100644 index 000000000..41755caf8 --- /dev/null +++ b/website/versioned_docs/version-0.75/native-code.md @@ -0,0 +1,76 @@ +--- +id: version-0.75-native-code +title: Working with native code on Windows +original_id: native-code +--- + +## What is a React Native for Windows app? + +When you create a React Native for Windows app targeting React Native's old architecture, you will get a [Universal Windows Platform app](https://docs.microsoft.com/windows/uwp/get-started/universal-application-platform-guide) (aka UWP app). + +The Universal Windows Platform allows you to access a set of common functionality on all Windows devices via the [Windows Runtime](https://docs.microsoft.com/windows/uwp/winrt-components/) (WinRT). WinRT APIs can be accessed from C++ (via [C++/WinRT](https://docs.microsoft.com/windows/uwp/cpp-and-winrt-apis/)), or via .NET C#. + +#### WinRT support in .NET +The current publicly supported version of .NET ([.NET UWP](https://docs.microsoft.com/windows/uwp/winrt-components/creating-windows-runtime-components-in-csharp-and-visual-basic)) has built-in support for WinRT. + + +## Win32 Desktop apps vs. RNW apps + +Whether you are new to Windows development, or you are a Win32 desktop app veteran, the following FAQs should answer some common questions. + +When you add Windows support to a React Native app via the steps described in [Get Started with Windows](getting-started.md), you will get a UWP app. + +> **Note:** By default the [init-windows command](init-windows-cli.md) creates a C++ app, however it is possible to create a C# app instead. The choice of language can impact your performance and your capacity to consume native modules, so if either of those issues are important to you, it's highly recommended that you read [Choosing C++ or C# for native code](native-code-language-choice.md). + +Regardless of the language of your app **RNW apps are UWP apps** and therefore have the following characteristics: + +### API surface +The set of APIs these app can access are a subset of all Windows APIs (i.e. those accessible via WinRT). See: +- [Win32 and COM APIs for UWP apps](https://docs.microsoft.com/uwp/win32-and-com/win32-and-com-for-uwp-apps) +- [CRT functions not supported in Universal Windows Platform apps](https://docs.microsoft.com/cpp/cppcx/crt-functions-not-supported-in-universal-windows-platform-apps) +- [Alternatives to Windows APIs in Universal Windows Platform (UWP) apps](https://docs.microsoft.com/uwp/win32-and-com/alternatives-to-windows-apis-uwp) + +### Isolation +The app runs inside of an app container - a type of sandbox. This provides apps with a secure way to install, access system resources like the filesystem, and lets the system manage their lifetime (e.g. suspending the app when it isn't on the foreground). This means that by default an RNW app cannot access arbitrary filesystem locations, start arbitrary processes, etc. UWP apps that need to access these kinds of capabilities may be able to do so via [App capability declarations](https://docs.microsoft.com/windows/uwp/packaging/app-capability-declarations). + +### Packaging + +React Native Windows apps are signed and packaged. [Packaging](https://docs.microsoft.com/windows/uwp/packaging/) is a mechanism through which an app and its dependencies acquire an identity, which is used to determine whether API calls that require system capabilities (e.g. filesystem access) should succeed or not. + +### Distribution +React Native Windows apps can be distributed, installed and updated in the following ways: + + - via [the Microsoft Store](https://docs.microsoft.com/windows/apps/desktop/modernize/desktop-to-uwp-distribute). + - via [your private Store](https://docs.microsoft.com/microsoft-store/distribute-apps-to-your-employees-microsoft-store-for-business) if you are a business or educational organization. See also [Distribute LOB apps to enterprises](https://docs.microsoft.com/windows/uwp/publish/distribute-lob-apps-to-enterprises). + - using [App Installer](https://docs.microsoft.com/windows/msix/app-installer/installing-windows10-apps-web). + +It's worth noting that you cannot just "_copy an EXE_" as the app package contains more than just the main executable, including an app manifest, assets, dependent framework libraries, etc. + +In addition, the Store submission process has these requirements: + +- UWP apps submitted to the store must pass [Windows App Certification Kit](https://docs.microsoft.com/windows/uwp/debug-test-perf/windows-app-certification-kit) (WACK) validation. +- UWP apps written in C# or other managed languages submitted to the store must be built using the [.NET Native toolchain](https://docs.microsoft.com/dotnet/framework/net-native/). This is the default when building C# apps in Release mode, **but not in Debug**, so apps built in Debug will be rejected by the Store. + +### Use of non-WinRT libraries +Any libraries you use should be built as WinRT components. In other words, you cannot easily link libraries built for Win32 desktop apps without additional work. + - C++/CX is a dialect of C++ that allows writing UWP apps, however this is **not supported** for writing a RNW app. The article [How to use existing C++ code in a Universal Windows Platform app](https://docs.microsoft.com/cpp/porting/how-to-use-existing-cpp-code-in-a-universal-windows-platform-app) talks about how to consume non-WinRT libraries in a WinRT context using C++/CX, but most of the content should be applicable to using C++/WinRT which is the supported way to write RNW apps. + - See also the guide for [moving from C++/CX to C++/WinRT](https://docs.microsoft.com/windows/uwp/cpp-and-winrt-apis/move-to-winrt-from-cx). + - Libraries built for .NET desktop framework cannot be directly accessed by UWP. You can create a .NET Standard library that calls into the .NET framework one, and call from the UWP app into the .NET Standard middleware. + +### Local testing and inner loop +For internal development, you can deploy your app for test purposes by side-loading and deploying via [loose-file registration](https://docs.microsoft.com/windows/uwp/debug-test-perf/loose-file-registration). When building in **Debug** mode (which is the default), the [run-windows command](run-windows-cli.md) performs loose-file registration of your app in order to install it locally. When building with the `--release` switch, the CLI will install the real package onto your local machine. This requires the app to be signed and for the certificate it uses for signing to be trusted by the machine the app is going to be installed on. See [Create a certificate for package signing](https://docs.microsoft.com/windows/msix/package/create-certificate-package-signing) and [Intro to certificates](https://docs.microsoft.com/windows/uwp/security/certificates). + +### Debugging crashes and reporting issues +If your app is "hard crashing" (the native code hits an error condition and your app closes), you will want to investigate the native side of the code. If the issue is in the `Microsoft.ReactNative` layer, please file a bug in the [React Native for Windows](https://github.com/microsoft/react-native-windows) repo, and provide a native stack trace, and ideally a crash dump with symbols. +For your convenience, you can use a script to collect a native crash dump and stack traces. Here are the instructions: + +1. Download the script at https://aka.ms/RNW/analyze-crash.ps1, for example to C:\temp +2. Open an admin PowerShell +3. If you haven't enabled running unsigned scripts yet, do that by running: `Set-ExecutionPolicy Unrestricted` +4. Run the script and pass it the name of your app's exe (usually it will be your app's name): `C:\temp\analyze-crash.ps1 -ExeName MyApp` + +The script will set up automatic crash dump collection for your app, download the native debugging tools (including the command line debugger cdb), and ask you to reproduce the crash. + +At this point you can launch the app (e.g. from Start menu if you've already deployed it to the local device). When the app crashes, it will generate a crash dump. You can then press enter to resume execution of the script, and the script will use cdb to automatically analyze the crash dump, and output the results to a file `analyze.log`. + +The script will then copy the contents of the log to the clipboard, open the log file in notepad, and launch the browser to file an issue in the react-native-windows repo, where you can paste the stack trace into the bug template. \ No newline at end of file diff --git a/website/versioned_docs/version-0.75/native-modules-autolinking.md b/website/versioned_docs/version-0.75/native-modules-autolinking.md new file mode 100644 index 000000000..9ce0cb8e0 --- /dev/null +++ b/website/versioned_docs/version-0.75/native-modules-autolinking.md @@ -0,0 +1,53 @@ +--- +id: version-0.75-native-modules-autolinking +title: Autolinking Native Modules +original_id: native-modules-autolinking +--- + +Autolinking is a mechanism that allows your React Native app project to discover and use native modules and view managers provided by React Native libraries. + +This document covers autolinking for the Windows platform. It is an extension to the [React Native CLI Autolinking doc](https://github.com/react-native-community/cli/blob/master/docs/autolinking.md). + +Add a library using your favorite package manager and run the build: + +```bat +yarn add react-native-webview +npx react-native run-windows +``` + +That's it. No more editing native files to use native code. + +## How does it work + +From the [React Native CLI Autolinking doc](https://github.com/react-native-community/cli/blob/master/docs/autolinking.md#how-does-it-work): + +> Each platform defines its own [`platforms`](https://github.com/react-native-community/cli/blob/master/docs/platforms.md) configuration. It instructs the CLI on how to find information about native dependencies. This information is exposed through the [`config`](https://github.com/react-native-community/cli/blob/master/docs/commands.md#config) command in a JSON format. It's then used by the scripts run by the platform's build tools. Each script applies the logic to link native dependencies specific to its platform. + +The information provided by `config` is described in [React Native Config Schema](config.md). + +## Autolinking process + +Autolinking is performed automatically as a part of the [run-windows command](run-windows-cli.md): + +1. At build time, autolinking is performed first, before `msbuild.exe` is invoked and the build actually started. It uses the information provided by `config` to both generate and modify certain native files consumed by your app project. + 1. The `AutolinkedNativeModules.g.targets` file contains the necessary references to the dependency projects that must be built. + > Your app's solution file may also be modified to ensure the dependency projects will be built. + + 1. The `AutolinkedNativeModules.g.(cpp|cs)` files contain a `RegisterAutolinkedNativeModulePackages` method which registers all of the specified `IReactPackageProvider`s from the dependencies. +1. At build time, while `msbuild.exe` is running, but before compiling your app project, a check will verify that the autolinked files are up-to-date, and warn you if they aren't. + > If you're using `run-windows` this check should always pass. However, if you've manually edited the generated files, or changed your npm dependencies and are building manually with Visual Studio, then the check might fail. See [manually run autolinking](#manually-run-autolinking). +1. At runtime, when your app is starting up it will call `RegisterAutolinkedNativeModulePackages`, registering the native dependencies with React Native, making them available to JS code. + +## Alternatives + +### Manually run autolinking + +If you would like to run the autolinking process outside of the build, you can run the [autolink-windows command](autolink-windows-cli.md) manually at any time. + +### Skipping autolinking + +If you would like to skip the autolinking process during [run-windows command](run-windows-cli.md) you can pass `--no-autolink` option: + +```bat +npx react-native run-windows --no-autolink +``` diff --git a/website/versioned_docs/version-0.75/native-modules-setup.md b/website/versioned_docs/version-0.75/native-modules-setup.md new file mode 100644 index 000000000..9d6969231 --- /dev/null +++ b/website/versioned_docs/version-0.75/native-modules-setup.md @@ -0,0 +1,176 @@ +--- +id: version-0.75-native-modules-setup +title: Native Module Setup +original_id: native-modules-setup +--- + +> **This documentation is a work in progress and version-specific. Please check that the version of this document (top of page) matches the version of RN/RNW you're targeting.** +> **Examples (C# and C++/WinRT):** +> +> - [Native Module Sample in `microsoft/react-native-windows-samples`](https://github.com/microsoft/react-native-windows-samples/tree/main/samples/NativeModuleSample) +> - [Sample App in `microsoft/react-native-windows/packages/microsoft-reactnative-sampleapps`](https://github.com/microsoft/react-native-windows/tree/main/packages/sample-apps) + +This guide will help set you up with the Visual Studio infrastructure to author your own stand-alone native module for React Native Windows. In this document we'll be creating the scaffolding for a `NativeModuleSample` native module. + +## Development Environment + +Make sure you have installed all of the [development dependencies](rnw-dependencies.md). + +## Choose your own adventure + +Once your development environment has been correctly configured, you have several options about how to access native APIs. You can either: + +- [Reference the APIs directly from within a React Native for Windows project](#referencing-windows-apis-within-a-react-native-for-windows-app-project) +- [Create a new native module library that can be distributed separately from your app](#creating-a-new-native-module-library-project) +- [Add Windows support to an existing community library](#adding-windows-support-to-an-existing-library) + +## Referencing Windows APIs within a React Native for Windows app project + +If you are only planning on adding a native module to your existing React Native Windows app, i.e.: + +1. You followed the [Getting Started](getting-started.md) guide, where +1. You used the [init-windows command](init-windows-cli.md) to add Windows to your project, and +1. You are just adding your native code to the app project under the `windows` folder. + +Then you can simply open the Visual Studio solution in the `windows` folder and add the new files directly to the app project. + +## Creating a new native module library project + +The steps to create a new native module library project are: +1. Follow the official React Native instructions to create a blank native module project +1. Add Windows support to the newly created library + +### Creating a blank native module project + +Follow the official React Native instructions at https://reactnative.dev/docs/native-modules-setup, + +or execute the following commands: + +```bat +npx create-react-native-module NativeModuleSample +cd NativeModuleSample +yarn install +``` + +Now you'll have a new native module project under `NativeModuleSample`. Be sure to look at the command output for further steps you'll want to do before publishing the project. + +At this point, follow the steps below to add Windows support to the newly created library. + +## Adding Windows support to an existing library + +> The steps below are written as if you're working with the `NativeModuleSample` example above, in the root folder of the project. Substitute the name of the library you're actually working on where appropriate, and ensure that you're working in the appropriate root folder of the library. + +### Updating your `package.json` + +Many native module libraries (including the default library template) target older versions of `react` and `react-native` than Windows supports, so you'll need to upgrade to newer versions in order to add support for `react-native-windows`. + +> Properly defining your NPM dependencies is an essential part of creating and maintaining a React Native library, especially one that supports multiple platforms. The instructions here represent the minimum steps required to start targeting `react-native-windows`. If you're adding Windows support to a library you don't own, you'll need to work with the library owners to make sure any changes made to `package.json` are appropriate. +> +> For more information on how NPM dependencies work, see [Specifying `dependencies` and `devDependencies` in a `package.json` file](https://docs.npmjs.com/specifying-dependencies-and-devdependencies-in-a-package-json-file). + +You can use the `npm info` command to find the correct versions to use. Let's assume you plan on building against the latest stable version of `react-native-windows`. + +Use the following command to find the matching versions of `react`: + +```bat +npm info react-native-windows@latest devDependencies.react +``` + +Take the result of that command (let's say it's `x.y.z`) and use it to upgrade the dev dependency: + +```bat +yarn upgrade react@x.y.z --dev +``` + +You'll need to repeat the steps for `react-native`, i.e.: + +```bat +npm info react-native-windows@latest devDependencies.react-native +``` + +Again, take the result of that command (let's say it's `0.x.y`) and use it to upgrade the dev dependency: + +```bat +yarn upgrade react-native@0.x.y --dev +``` + +Next add `react-native-windows` to your dependencies: + +```bat +yarn add react-native-windows@latest +yarn install +``` + +Now you should be ready to add Windows support with the [init-windows command](init-windows-cli.md). The process is similar to adding Windows support to an app project, but you'll need to specify a library template: + +```bat +npx react-native init-windows --template old/uwp-cpp-lib --overwrite +``` + +This defaults to a C++/WinRT project. If you want to create a C# based native module project, use: + +```bat +npx react-native init-windows --template old/uwp-cs-lib --overwrite +``` + +That's it, you should be able to open `windows\NativeModuleSample.sln` and start working on your project. + +### Testing your Build + +To make sure that everything is working, you'll want to try building `NativeModuleSample`. First you'll want to make sure you've chosen a supported platform: + +1. At the top, change the `Solution Platform` to `x86` or `x64`. +1. In the `Build` menu, select `Build Solution`. + +### Next Steps + +You have now created the scaffolding to build a native module or view manager. Now it's time to add the business logic to the module - follow the steps described in the [Native Modules](native-modules.md) and [View Managers](view-managers.md) documents. + +### Making your module ready for consumption in an app + +If you've followed the steps above, your module should be ready for consumption thanks to [Autolinking](native-modules-autolinking.md). + +However, there are some things you may need to check: + +#### 1. Fixing relative NuGet paths + +If you are writing a C++/WinRT module and have added any NuGet package dependencies, you'll see references to those packages in your vcxproj file as relative references e.g. `..\packages\...`. We need these to use the solution directory instead, so replace all mentions of `..\packages\` with `$(SolutionDir)\`. + +**Example:** + +```diff +- ++ +``` + +### Testing the module before it gets published + +#### Option 1: Create a new test app +1. Follow the [getting started guide](getting-started.md) to create a new React Native Windows app. +2. Run `npm i --save` (e.g. `npm i D:\NativeModuleSample --save`) to install the local module. +3. [Link the native module](native-modules-using.md). + +#### Option 2: Adding Windows support to existing sample app + +If you are working on an existing module that already has iOS and Android samples, and want to add Windows support to the existing test app, follow these steps (example of WebView module test app can be found [here](https://github.com/react-native-community/react-native-webview/tree/master/example)). + +1. In a different directory, follow the [getting started guide](getting-started.md) and create a new React Native Windows app. +2. Copy the `Windows` folder from the blank RNW app into the existing sample app's sample app's folder. (The RNW CLI helps create the correct project setup that you can then copy directly into the sample app.) +3. Open `sln` and `vxcproj` files and check `node_module` reference paths. Fix the paths if necessary based on how the folders are structured in native module repo ([example](https://github.com/react-native-community/react-native-webview/blob/v11.17.2/example/windows/WebViewWindows.sln#L11-L42)). +4. Open the solution with Visual Studio and [link native module](native-modules-using.md). +> The project should build correctly at this point, but we still need to setup some special metro configurations for Windows in order to run the app without breaking iOS and Android bundling. + +5. Add `metro.config.windows` for Windows bundling ([example](https://github.com/react-native-community/react-native-webview/blob/v11.17.2/metro.config.windows.js)). Make sure the config file is at the root of the repo (see [Metro bug #588](https://github.com/facebook/metro/issues/588)). +6. In `package.json`, add a separate start command for windows and attach a special argument to tell metro to use the windows config we just created ([example](https://github.com/react-native-community/react-native-webview/blob/v11.17.2/package.json#L18)). +7. Add `react-native.config.js` to parse the special argument we added ([example](https://github.com/react-native-community/react-native-webview/blob/v11.17.2/react-native.config.js#L28-L33)). +8. Update JS main module path (relative path to metro `projectRoot`) in `App.cpp` if necessary ([example](https://github.com/react-native-community/react-native-webview/blob/v11.17.2/example/windows/WebViewWindows/App.cpp#L25)). + +### Adding tests for your module +We are using WebdriverIO + WinAppDriver for UI testing. More details [here](https://github.com/microsoft/react-native-windows/blob/main/docs/e2e-testing.md#appium). For real world examples, check out [`react-native-webview`](https://github.com/react-native-community/react-native-webview) or [progress-view](https://github.com/react-native-community/progress-view). + +### Setup CI (continuous integration) pipeline for your module + +When done developing your module, it's good practice to setup a CI pipeline with automated build and tests to avoid any future regressions. See the [Setup Continuous Integration Pipeline for an RNW App](setup-ci.md) for more information. + +### Documenting Your Module +Once your module is complete, update [react-native-community/directory](https://github.com/react-native-community/directory) so that its information on your native module is up to date. If you are building a native module which will be maintained by Microsoft, please update the Supported Community Modules documentation in [react-native-windows-samples](https://github.com/microsoft/react-native-windows-samples/blob/main/docs/supported-community-modules.md) with your native module's information. diff --git a/website/versioned_docs/version-0.75/native-modules-using.md b/website/versioned_docs/version-0.75/native-modules-using.md new file mode 100644 index 000000000..d15b471d1 --- /dev/null +++ b/website/versioned_docs/version-0.75/native-modules-using.md @@ -0,0 +1,41 @@ +--- +id: version-0.75-native-modules-using +title: Using Community Native Modules +original_id: native-modules-using +--- + +Community native modules are usually distributed as npm packages. To understand more about npm packages you may find [this guide](https://docs.npmjs.com/packages-and-modules/contributing-packages-to-the-registry) useful. + +Consuming native modules requires updating your app's native build files to depend on the module's native build files, called "linking". Many modules support "autolinking", where these updates are done automatically when running the [run-windows command](run-windows-cli.md). Others may require you to link the module manually. + +This document outlines the general steps to manually link a module (`react-native-foo`) to your project. + +> Not all community modules have been updated to work with Windows. If you find a module that doesn't work with Windows, please file an [issue on GitHub](https://github.com/microsoft/react-native-windows/issues/new/choose). We're tracking the list of incompatible modules that we're working to add support for [on GitHub](https://github.com/microsoft/react-native-windows/projects/23). + +> Note that individual modules may have different or specific steps for linking to Windows. The steps outlined in this doc are useful if the module repo doesn't outline how to use the module on Windows. + +> For more information on how autolinking works, see [Autolinking Native Modules](native-modules-autolinking.md). + +## Step 1: Update the solution file + +Add the `ReactNativeFooCPP` project to your solution. + +1. Open the solution in Visual Studio 2019 +2. Right-click Solution icon in Solution Explorer > Add > Existing Project +3. Select `node_modules\react-native-foo\windows\vNext\ReactNativeFooCPP\ReactNativeFooCPP.vcxproj` + +## Step 2: Update the .vcxproj file + +Add a reference to `ReactNativeFooCpp` to your main application project. From Visual Studio 2019: + +1. Right-click main application project > Add > Reference... +2. Check `ReactNativeFooCpp` from Solution Projects + + +## Step 3: Update the `pch.h` file + +Add `#include "winrt/ReactNativeFooCPP.h"`. + +## Step 4: Register the package + +Add `PackageProviders().Append(winrt::ReactNativeFooCPP::ReactPackageProvider());` before `InitializeComponent();`. diff --git a/website/versioned_docs/version-0.75/nuget-update.md b/website/versioned_docs/version-0.75/nuget-update.md new file mode 100644 index 000000000..5dcd19718 --- /dev/null +++ b/website/versioned_docs/version-0.75/nuget-update.md @@ -0,0 +1,93 @@ +--- +id: version-0.75-nuget-update +title: Updating NuGet packages +original_id: nuget-update +--- + +>**This documentation and the underlying platform code is a work in progress.** + +The versions of the [NuGet](nuget.md) packages used in your project must match the version of the `react-native-windows` npm package. For React Native for Windows versions >= 0.68, the default app template takes care of this for you automatically. However if you're not using the supported template, the steps below may help you consume the NuGet packages manually. + +# Determine npm version +You can find the npm version by opening `package.json` at the root of your project and looking in the dependencies section: +```json +{ + "name": "MyProject" + ... + "dependencies": { + ... + "react-native-windows": "0.63.0" + }, + ... +``` +In this example the npm version for `react-native-windows` is `0.63.0`. Note that if you use preview, Your version might include a preview marker like `0.64.0-preview.3`. + +# Determine and update the NuGet version +For Windows there are two project types: C++ and C#. If you don't know which one you can look in the `windows/MyProject` folder. +If you find a `MyProject.vcxproj` file, you have a C++ project. +If you find a `MyProject.csproj` file, you have a C# project. +Each project type has different instructions. For either you can use both the Visual Studio IDE or a text editor. +Note: The [Visual Studio IDE](https://visualstudio.microsoft.com/vs/) only runs on Windows and is not the same as [Visual Studio Code](https://code.visualstudio.com/?wt.mc_id=DX_841432). +If you use [Visual Studio for Mac](https://visualstudio.microsoft.com/vs/mac/), please follow the text editor instructions. + +* C# + * [Text editor](#c-project---text-editor) + * [Visual Studio IDE](#c-project---visual-studio-ide) +* C++ + * [Text editor](#c-project---text-editor-1) + * [Visual Studio IDE](#c-project---visual-studio-ide-1) + + +## C# project - Text editor +1. Open `windows/MyProject/MyProject.csproj` in a text editor +1. Find the Package reference section: + ```xml + + 0.63.0 + + ``` +1. Change the version element. + +## C# project - Visual Studio IDE +1. Open the solution in Visual Studio +1. Right-Click on the C# project file `MyProject (Universal Windows)` in the Solution Explorer window + + ![Visual Studio Solution Explorer showing the csproj project selected](assets/nuget-update-cs-project.png) +1. Select "Managed NuGet Packages..." +1. Select the "Installed" tab + + ![Visual Studio Manage NuGet dialog showing the installed tab selected](assets/nuget-update-packages-manager-installed-tab.png) +1. If the npm version has a hyphen with a preview marker, you must check the "Include Prerelease" per the image above. +1. Select the package `Microsoft.ReactNative.Managed` +1. Select the version of your npm package in the version drop-down on the right side. + + ![Visual Studio Managed NuGet dialog with the version drop-down selected.](assets/nuget-update-select-package.png) +1. Click `install` +1. Close the dialog and save your project + +## C++ project - Text editor +1. Open `windows/MyProject/packages.config` in a text editor. +1. Update the version attributes of both `Microsoft.ReactNative` and `Microsoft.ReactNative.Cxx` packages +1. Open `windows/MyProject/MyProject.vcxproj` in a text editor. +1. Perform a search and replace for: + * `packages\Microsoft.ReactNative.0.63.0` + * `packages\Microsoft.ReactNative.Cxx.0.63.0` + and replace it with the the version number of the npm package. + There should be multiple strings to replace. + +## C++ project - Visual Studio IDE +1. Open the solution in Visual Studio +1. Right-Click on the C++ project file `MyProject (Universal Windows)` in the Solution Explorer window + + ![Visual Studio Solution Explorer showing the vcxproj project selected](assets/nuget-update-cpp-project.png) +1. Select "Managed NuGet Packages..." +1. Select the "Installed" tab + + ![Visual Studio Manage NuGet dialog showing the installed tab selected](assets/nuget-update-packages-manager-installed-tab.png) +1. If the npm version has a hyphen with a preview marker, you must check the "Include Prerelease" per the image above. +1. Perform the next two steps for both `Microsoft.ReactNative` and `Microsoft.ReactNative.Cxx` packages: + 1. On the right side, from the version drop-down select the version of your npm package + + ![Visual Studio Managed NuGet dialog with the version drop-down selected.](assets/nuget-update-select-package.png) + 1. Click `install` +1. Close dialog and save your project diff --git a/website/versioned_docs/version-0.75/nuget.md b/website/versioned_docs/version-0.75/nuget.md new file mode 100644 index 000000000..8976df609 --- /dev/null +++ b/website/versioned_docs/version-0.75/nuget.md @@ -0,0 +1,61 @@ +--- +id: version-0.75-NuGet +title: Using Microsoft.ReactNative NuGet packages +original_id: NuGet +--- + +>**This documentation and the underlying platform code is a work in progress.** + +The default for React Native Windows has been to build all code from source. This includes building all the code shipped by the team in the npm package from source. This code can be quite large and take a long time to build as well as require a high-performance computer. Some configurations have problems building this code with only 8 GB of memory. Especially if you are used to working only with managed code, this can be a big surprise. + +Starting with version 0.64 the team offers experimental NuGet packages that can be used as a replacement of compiling the sources. + +> Disclaimer: There are known compatibility issues with [community modules](supported-community-modules.md), as they still rely on building the shared code from source. So the solution still needs to have all the source projects which puts all the build performance problems back. + +The benefit of using NuGet packages is that you get improved compilation times for your Windows project and can develop on a less powerful computer. + +The other benefit will be that it will be easier to update your projects to future versions of `react-native-windows`. + +# How to enable on new projects + When creating a new project in [Get Started with Windows](getting-started.md), the templates used by the [init-windows command](init-windows-cli.md) default to building against source. Follow the instructions below if you wish to try using the NuGet packages. + +> Note: The formerly recommended [React Native Windows Init CLI](https://microsoft.github.io/react-native-windows/init-cli) still supports an `--experimentalNuGetDependency true` flag to set up a new project which uses the NuGet packages, but as that command is planned for deprecation, it's not recommended. + +# How to update a previously created project +The steps below will help you modify your RNW project so you can consume the RNW NuGet packages. + +> Note: If you're in the process of upgrading your app to a new version of RNW (See [Upgrading App to Latest Version of React Native Windows](upgrade-app.md)), and you've already set the `true` flag (as per below), the [init-windows command](init-windows-cli.md) will try to respect that setting so you shouldn't have to re-apply the manual steps below after the upgrade. + + + +1. Update the solution file `windows\.sln`: + 1. Open the project in Visual Studio + 1. Remove all projects except your own app project +1. Edit the file `windows\ExperimentalFeatures.props` + 1. Set the following to true + ```xml + true + ``` +1. Edit the project file `windows\\` + 1. Remove any `` or `` references for `Microsoft.ReactNative.*` projects. + +1. Update the C# logic for the new [compile-time C# codeGen](native-modules-csharp-codegen.md) + + +> Note: Starting with version 0.68, React Native for Windows apps use `PackageReference`s for native `C++` NuGet dependencies. See [Managing C++ dependencies](managing-cpp-deps.md) about migrating away from use the older, `packages.config` for managing NuGet dependencies. + +1. Update the solution file `windows\.sln`: + 1. Open the project in Visual Studio + 1. Remove all projects that are not your project +1. Edit the file `windows\ExperimentalFeatures.props` + 1. Set the following to true + ```xml + true + ``` +1. Edit the project file `windows\\` + 1. Remove any `` or `` references for `Microsoft.ReactNative.*` projects. + + + +# Version match +The versions of the NuGet package in your project must match the npm package version. If you need to update the NuGet packages there is a separate page on [Updating NuGet packages](nuget-update.md) diff --git a/website/versioned_docs/version-0.75/react-native-windows-cli.md b/website/versioned_docs/version-0.75/react-native-windows-cli.md new file mode 100644 index 000000000..0a7af5b13 --- /dev/null +++ b/website/versioned_docs/version-0.75/react-native-windows-cli.md @@ -0,0 +1,33 @@ +--- +id: version-0.75-react-native-windows-cli +title: React Native Windows CLI +original_id: react-native-windows-cli +--- + +When React Native for Windows is added to a React Native project, a variety of Windows-specific developer commands are added to the `react-native` CLI. + +> The following commands are provided by the the `@react-native-windows/cli` NPM package. + +## `react-native autolink-windows` + +Runs Windows-specific autolinking for your RNW project. + +See the [react-native autolink-windows docs](autolink-windows-cli.md) for detailed usage information. + +## `react-native codegen-windows` + +Runs Windows-specific codegen for native modules. + +See the [react-native codegen-windows docs](codegen-windows-cli.md) for detailed usage information. + +## `react-native init-windows` + +Initializes a new RNW project from a given template. + +See the [react-native init-windows docs](init-windows-cli.md) for detailed usage information. + +## `react-native run-windows` + +Builds your RNW app and starts it on a connected Windows desktop, emulator, or device. + +See the [react-native run-windows docs](run-windows-cli.md) for detailed usage information. diff --git a/website/versioned_docs/version-0.75/releases.md b/website/versioned_docs/version-0.75/releases.md new file mode 100644 index 000000000..75223f0d6 --- /dev/null +++ b/website/versioned_docs/version-0.75/releases.md @@ -0,0 +1,16 @@ +--- +id: version-0.75-releases +title: Release Strategy +original_id: releases +--- + +For every major version update of `react-native`, React Native for Windows releases a matching version. In addition, there are three release distributions with corresponding npm package distribution tags: +1. Canary (@canary) +2. Preview (@preview) +3. Latest (@latest) + +`canary` builds are built directly from our main branch. These builds provide no guarantees around upstream React version, breaking changes, or overall stability. These builds should be used for development or to test bleeding edge functionality but should not be relied upon for production use. Master builds are versioned as `0.0.0-canary.x`. + +`preview` builds are the first released by stable branches. These builds aim to become increasingly polished over time and have fewer breaking changes than in canary. Preview builds are versioned as `0.x.0-preview.y`, where x matches the minor release of React Native. + +`latest` builds corresponding to our "released" version. Breaking changes should not be made to stable branches after promotion to latest. Caution must be taken to not compromise the stability of our non-prerelease branches. Only low risk changes critical to customer scenarios should be back-ported. Released builds are versioned as `0.x.y` where x matches the minor release of React Native. diff --git a/website/versioned_docs/version-0.75/run-windows-cli.md b/website/versioned_docs/version-0.75/run-windows-cli.md new file mode 100644 index 000000000..366d708a2 --- /dev/null +++ b/website/versioned_docs/version-0.75/run-windows-cli.md @@ -0,0 +1,56 @@ +--- +id: version-0.75-run-windows-cli +title: react-native run-windows +original_id: run-windows-cli +--- + +This guide will give you more information on the `run-windows` command of the React Native Windows CLI. + +## `run-windows` + +The `run-windows` CLI command is used to build and run React Native for Windows apps. + +### Usage +Builds your RNW app and starts it on a connected Windows desktop, emulator, or device. + +```bat +npx react-native run-windows +``` +### Options + +> **Note:** Remote Debugging was officially marked as [deprecated](https://github.com/react-native-community/discussions-and-proposals/discussions/734) in RN 0.73 and will be removed in a later release. + +Here are the options that `react-native run-windows` takes: +| Option | Input Type | Description | +|-----------------------|------------|--------------------------------------------------| +| `--release` | boolean | Specifies a Release build | +| `--root` | string | Override the root directory for the project which contains the `windows` folder | +| `--arch` | string | The build architecture, i.e. `ARM64`, `x86`, `x64`. Defaults to system architecture | +| `--singleproc` | boolean | Disables multi-proc build | +| `--emulator` | boolean | Deploys the app to an emulator | +| `--device` | boolean | Deploys the app to a connected device | +| `--target` | string | Deploys the app to the specified `GUID` for a device | +| `--remote-debugging` | boolean | **(Deprecated)** Deploys the app in remote debugging mode | +| `--logging` | boolean | Verbose output logging | +| `--no-packager` | boolean | Do not launch the packager while building | +| `--bundle` | boolean | Enable Bundle configuration, i.e. `ReleaseBundle`/`DebugBundle` rather than `Release`/`Debug` | +| `--no-launch` | boolean | Do not launch the app after deployment | +| `--no-autolink` | boolean | Do not run autolinking | +| `--no-build` | boolean | Do not build the solution | +| `--no-deploy` | boolean | Do not deploy the app | +| `--deploy-from-layout`| boolean | Force deploy from layout even in Release builds | +| `--sln` | string | Override the app solution file determined by 'react-native config', i.e. `windows\myApp.sln` | +| `--proj` | string | Override the app project file determined by 'react-native config', i.e. `windows\myApp\myApp.vcxproj` | +| `--msbuildprops` | string | Comma separated props to pass to MSBuild, i.e. `prop1=value1,prop2=value2` | +| `--buildLogDirectory` | string | Optional directory where MSBuild log files should be stored | +| `--info` | boolean | Dump environment information | +| `--direct-debugging` | number | Enable direct debugging on specified port | +| `--no-telemetry` | boolean | Disables sending telemetry that allows analysis of usage and failures of the react-native-windows CLI | +| `-h`, `--help` | boolean | Display help for command | + +This sends telemetry to Microsoft by default. You can prevent the telemetry from being sent by using the `--no-telemetry` command line option. See below for more details. + +The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices. + +This data collection notice only applies to the process of running the react-native-windows CLI commands. + \ No newline at end of file diff --git a/website/versioned_docs/version-0.75/setup-ci.md b/website/versioned_docs/version-0.75/setup-ci.md new file mode 100644 index 000000000..b797bb232 --- /dev/null +++ b/website/versioned_docs/version-0.75/setup-ci.md @@ -0,0 +1,117 @@ +--- +id: version-0.75-setup-ci +title: Setup Continuous Integration Pipeline for an RNW App +original_id: setup-ci +--- + +This guide will help you get started on setting up your very first continuous integration pipeline for a React Native for Windows app. + +## Setting Up a Continuous Integration Pipeline using GitHub Actions + +When done developing your app, it's good practice to setup a CI pipeline with automated builds and tests to avoid any future regressions. There are many services available for setting up a CI pipeline. We'll use [GitHub Actions](https://docs.github.com/actions) as an example here since it doesn't require any extra account setup if you are already hosting your code on GitHub, also the default VM image has all the tools we needed pre-installed. + +The VM images supported by GitHub Actions CI/CD can be found [here](https://github.com/actions/virtual-environments#github-actions-virtual-environments), check the pre-installed tools and compare them with [React Native Windows development dependencies](https://microsoft.github.io/react-native-windows/docs/rnw-dependencies), find the image that meets the requirements. + +Next you need to create a YAML file for GitHub Actions, the basic steps are: +- Checkout code and setup the environment +```yaml + name: Windows CI + on: [pull_request] + + jobs: + run-windows-tests: + name: Build & run tests + runs-on: windows-2022 + + steps: + - uses: actions/checkout@v2 + name: Checkout Code + + - name: Setup Node.js + uses: actions/setup-node@v1 + with: + node-version: '^18' + + - name: Setup MSBuild + uses: microsoft/setup-msbuild@v2 + + - name: Install node modules + run: yarn --frozen-lockfile +``` +- Build and run the project +```yaml + - name: Run Windows x64 release + run: npx react-native run-windows --arch x64 --release --logging +``` +Check out the full [`react-native-webview` example](https://github.com/react-native-webview/react-native-webview/blob/master/.github/workflows/windows-ci.yml) as well as their [official example](https://github.blog/2019-08-08-github-actions-now-supports-ci-cd/) for more info. + +Save the YAML file to `.github\workflows\` and then commit. To learn more about YAML syntax, see [Workflow syntax for GitHub Actions](https://docs.github.com/actions/using-workflows/workflow-syntax-for-github-actions). + +> GitHub Actions should be enabled by default, if it's not enabled for some reason you can go to Settings->Actions tab of the repo to enable it (requires owner access). + +Now push your changes and the CI pipeline should be up and running. + +## Setting Up Pipeline for Signed Package Builds +[Certificates](https://docs.microsoft.com/windows/msix/package/create-certificate-package-signing) are used to sign RNW apps so that they can be installed locally or published to the Microsoft Store. This data should not be publicly published, so we need to do extra steps if we wish to build/run signed RNW app packages through GitHub Actions. + +### Storing Certificates Securely +There are a several options where you can securely store your certificate information: + +- [GitHub Secrets](https://docs.github.com/actions/security-guides/encrypted-secrets) +- [Azure Secure Files](https://docs.microsoft.com/azure/devops/pipelines/library/secure-files?view=azure-devops) +- [Azure Key Vault Secrets](https://docs.microsoft.com/azure/key-vault/secrets/about-secrets) + +GitHub Secrets works well, when you are using GitHub Actions to run your pipeline. The latter two work well, if you are using Azure DevOps to run your pipeline. + +For Azure Secure Files, you will upload the `.pfx` itself. The remaining two methods expect data in the form of a string. Thus, you must `Base64` encode your `.pfx` and upload the resulting string as your secret by running +```powershell +$fileContentBytes = get-content '' -Encoding Byte +[System.Convert]::ToBase64String($fileContentBytes) | Out-File pfx-encoded-bytes.txt +``` +in PowerShell. Then upload the contents of `pfx-encoded-bytes.txt` as your secret. + +### Accessing Certificate Data from Pipeline +For Azure Secure Files, retrieving the secret will download the `.pfx` itself. The remaining two methods will give you the encoded string. Thus, you'll have to decode the secret, and save it to a `.pfx` file before it can be used to sign. +In a YAML file the basic steps to generate your certificate from an encoded string stored in GitHub Actions are: +```yaml +- name: Decode the pfx + run: | + $PfxBytes = [System.Convert]::FromBase64String("${{ secrets.Base64_Encoded_Pfx }}") + $PfxPath = [System.IO.Path]::GetFullPath( (Join-Path -Path ProjectDirectoryPath -ChildPath GitHubActionsWorkflow.pfx) ) + [System.IO.File]::WriteAllBytes("$PfxPath", $PfxBytes) +``` +where your encoded string is a GitHub secret named `Base64_Encoded_Pfx`. + +In a YAML file the basic steps to use your certificate for a signed RNW app build are: +```yaml +steps: +- name: run-windows (Release) - CI + run: yarn windows --no-launch --arch x64 --logging --release --msbuildprops PackageCertificateKeyFile=ProjectDirectoryPath\GitHubActionsWorkflow.pfx +``` + +Make sure to delete your `.pfx` from the pipeline once you've finished using it. +In a YAML file the basic steps for removing your certificate are: +```yaml +- name: Remove the pfx + run: | + $certificatePath = Join-Path -Path ProjectDirectoryPath -ChildPath GitHubActionsWorkflow.pfx + Write-Host $certificatePath + Remove-Item -path $certificatePath +``` + +See the [`Xaml-Islands-Samples`](https://github.com/microsoft/Xaml-Islands-Samples/blob/1a112338455aacdde51cb13214bb9b57ba174a2c/.github/workflows/CPP-CI.yml) repository for an example of a pipeline which uses GitHub Secrets. +See the [`react-native-gallery`](https://github.com/microsoft/react-native-gallery/blob/bb9d933b33ee5f5bcb69903afe8bee351990719c/ci.yml) repository for an example of a pipeline which uses Azure DevOps Secure Files. +See the react-native-windows repository for an example of a pipeline which uses Azure Key Vault: +[Setup of Certificate](https://github.com/microsoft/react-native-windows/blob/d3c720b909b3c8de50cac5665c849288eabcf5da/.ado/templates/write-certificate.yml) +[Removal of Certificate](https://github.com/microsoft/react-native-windows/blob/d3c720b909b3c8de50cac5665c849288eabcf5da/.ado/templates/cleanup-certificate.yml) +[Signed RNW App Build](https://github.com/microsoft/react-native-windows/blob/d3c720b909b3c8de50cac5665c849288eabcf5da/.ado/templates/run-windows-with-certificates.yml) + +## FAQ's +### I'm ready to do a signed app build. How do I tell MSBuild to use my certificate? +You can tell MSBuild what `.pfx` you want to use to sign your app using the `PackageCertificateKeyFile` MSBuild property. This property expects the file path to the `.pfx` you want to use. See [here](https://github.com/microsoft/react-native-windows/blob/353321ee40391f6f302e7cc80f96285e12780cbe/.ado/jobs/playground.yml#L114) for an example of this using `VSBuild`. See [here](https://github.com/microsoft/react-native-windows/blob/353321ee40391f6f302e7cc80f96285e12780cbe/.ado/templates/run-windows-with-certificates.yml#L48) for an example of this using the RNW CLI. + +### I have a pipeline that runs on forks of my repository (i.e. when a PR is being made). Can I access my certificate data from this pipeline? +No. When data is securely stored through GitHub Secrets, Azure DevOps Secure Files, or Azure Key Vault, it can only be run from pipelines that are executing on branches of the original repository. The data cannot be accessed from pipelines running code from repository forks, because if the data was able to be accessed, someone could manipulate the pipeline source code within their fork to retrieve the data, leaving it unsecured. + +### I want to build a deployable package for my app from a pipeline that doesn't have access to my certificate data. What can I do? +This case may apply to you if you want to do some End To End testing within a PR pipeline to make sure incoming changes don't break your project. You do have a couple of options here to make do without a certificate. You can successfully build and deploy a non-signed RNW app via deploying from layout. The RNW CLI will by default deploys from layout as long as the MSBuild argument `AppxPackageSigningEnabled` or `PackageCertificateFile` is not set in the project file. If this is not the case for your app, you can force deploy from layout by using the `--deploy-from-layout` CLI option. diff --git a/website/versioned_docs/version-0.75/upgrade-app.md b/website/versioned_docs/version-0.75/upgrade-app.md new file mode 100644 index 000000000..d201b95a8 --- /dev/null +++ b/website/versioned_docs/version-0.75/upgrade-app.md @@ -0,0 +1,25 @@ +--- +id: version-0.75-upgrade-app +title: Upgrading App to Latest Version of React Native Windows +original_id: upgrade-app +--- +## Upgrading A React Native Windows App +Upgrading your app to new React Native Windows versions requires a small amount of effort, but we will try to streamline this process for you as much as possible in this guide. You have two main options for how to upgrade your React Native Windows app. You can use the [init-windows command](init-windows-cli.md) or manually upgrade using [Upgrade Helper](https://reactnative.dev/docs/upgrading#upgrade-helper). + +### Steps to Upgrade An App to New React Native Windows Version via CLI +1. In the root of your project, run the [init-windows command](init-windows-cli.md) (make sure you're using the correct template). +2. In the root of your project, run the [autolink-windows command](autolink-windows-cli.md) to link any native modules used by your app. +3. Step 1 will overwrite any changes you previously made to the native Windows code of your project and generate a new GUID. If you made changes to this code or wish to keep your previous GUID, you have two options: + + 1. Add those changes manually. + 2. If your project is a Git repository, open the project in Visual Studio Code and navigate to the Source Control tab. There, you can undo the specific overwrite edits that erased your changes. +3. The upgrade script will not remove any files that were removed from the new template. To check if there are any files that require manual deletion, use [Upgrade Helper](https://react-native-community.github.io/upgrade-helper/). See the section below for the steps on how to use this tool. +4. Your app is now ready to build! + +### Steps to Manually Upgrade An App to New React Native Windows Version via Upgrade Helper +1. Open [Upgrade Helper](https://react-native-community.github.io/upgrade-helper/) in your preferred browser. +2. Select the React Native Windows version your app is currently on and the version you wish to upgrade to. By default, the latest major versions are selected. +3. Select the "Show me how to upgrade" button. +4. Manually edit your app source to match the changes displayed in Upgrade Helper. +5. Run `yarn` at the root of your project to update your dependencies. +6. Your app is now ready to build! diff --git a/website/versioned_docs/version-0.75/view-managers.md b/website/versioned_docs/version-0.75/view-managers.md new file mode 100644 index 000000000..3cff671c9 --- /dev/null +++ b/website/versioned_docs/version-0.75/view-managers.md @@ -0,0 +1,671 @@ +--- +id: version-0.75-view-managers +title: Native UI Components +original_id: view-managers +--- + +> **This documentation and the underlying platform code is a work in progress.** +> **Examples (C# and C++/WinRT):** +> +> - [Native Module Sample in `microsoft/react-native-windows-samples`](https://github.com/microsoft/react-native-windows-samples/tree/main/samples/NativeModuleSample) +> - [Sample App in `microsoft/react-native-windows/packages/microsoft-reactnative-sampleapps`](https://github.com/microsoft/react-native-windows/tree/main/packages/sample-apps) + +There are tons of native UI widgets out there ready to be used in the latest apps - some of them are part of the platform, others are available as third-party libraries, and still more might be in use in your very own portfolio. React Native has several of the most critical platform components already wrapped, like `ScrollView` and `TextInput`, but not all of them, and certainly not ones you might have written yourself for a previous app. Fortunately, we can wrap up these existing components for seamless integration with your React Native application. + +Like the [native module guide](native-modules.md), this too is a more advanced guide that assumes you are somewhat familiar with UWP programming. This guide will show you how to build a native UI component, walking you through the implementation of a subset of the existing `ImageView` component available in the core React Native library. + +## Overview + +Similarly to authoring native modules, at a high level you must: + +1. Author a view manager which defines a new Component type and understands how to create and interact with the native UI widget. +2. Register your new view manager within the native code of your React Native host application. +3. Reference the new component within your React Native JSX code. + +### Note about UWP XAML controls +Some UWP XAML controls do not support being hosted in environments where 3D transforms are involved (i.e. the [`Transform3D`](https://docs.microsoft.com/en-us/uwp/api/windows.ui.xaml.uielement.transform3d) property is set on the control or on any of the control's ancestors in the XAML tree). + +Currently, React Native for Windows uses a global `PerspectiveTransform` to provide a 3D look to objects being rotated along the `x` or `y` axes, which means these controls that do not work in 3D environments, will not work out of the box (e.g. [`InkCanvas`](https://docs.microsoft.com/en-us/uwp/api/Windows.UI.Xaml.Controls.InkCanvas)). However, a React Native for Windows app can opt out of the 3D perspective (and in so doing, enable using these controls) by setting the [`IsPerspectiveEnabled`](https://github.com/microsoft/react-native-windows/blob/4e775b9a59c55996d7598aadaeb82c93c40cbb6f/vnext/Microsoft.ReactNative/ReactRootView.idl#L18) property on the `ReactRootView`. + +__Important__: The `IsPerspectiveEnabled` property is experimental and support for it may be removed in the future. + +## Initial Setup + +Prerequisite: Follow the [Native Modules Setup Guide](native-modules-setup.md) to create the Visual Studio infrastructure to author your own stand-alone native module for React Native Windows + +Once you have set up your development environment and project structure, you are ready to write code. + +If you are only planning on adding a native module to your existing React Native Windows app, i.e.: + +1. You followed [Getting Started](getting-started.md), where +1. You used the [init-windows command](init-windows-cli.md) to add Windows to your project, and +1. You are just adding your native code to the app project under the `windows` folder. + +Then you can simply open the Visual Studio solution in the `windows` folder and add the new files directly to the app project. + +If you are instead creating a standalone native module, or adding Windows support to an existing native module, check out the [Native Modules Setup](native-modules-setup.md) guide first. + +## Sample view manager + + + + +### Attributes + +| Attribute | Use | +| --------------------------------- | --------------------------------------------------------------------------------------- | +| `ViewManagerExportedViewConstant` | Specifies a field or property that represents a constant. | +| `ViewManagerProperty` | Specifies a method to be called to set a property on an instance of a native UI widget. | +| `ViewManagerCommand` | Specifies a method that can be called on an instance of a native UI widget. | + +For this sample, assume we have the following `CustomUserControl` that we want to use in React Native. + +`CustomUserControl.cs`: + +```csharp +using Windows.UI.Xaml; +using Windows.UI.Xaml.Controls; + +namespace ViewManagerSample +{ + public sealed class CustomUserControl : Control + { + public static DependencyProperty LabelProperty { get; private set; } + + public string Label + { + get + { + return (string)GetValue(LabelProperty); + } + set + { + SetValue(LabelProperty, value); + } + } + + static CustomUserControl() + { + LabelProperty = DependencyProperty.Register( + nameof(Label), + typeof(string), + typeof(CustomUserControl), + new PropertyMetadata(default(string)) + ); + } + + public CustomUserControl() + { + DefaultStyleKey = typeof(CustomUserControl); + } + } +} +``` + +```xml + + + + +``` + +### 1. Authoring your View Manager + +Here is a sample view manager written in C# called `CustomUserControlViewManager`. + +`CustomUserControlViewManager.cs`: + +```csharp +using Windows.UI.Xaml.Media; +using Windows.UI.Xaml.Controls; + +using Microsoft.ReactNative.Managed; +using System.Collections.Generic; + +namespace ViewManagerSample +{ + internal class CustomUserControlViewManager : AttributedViewManager + { + [ViewManagerProperty("label")] + public void SetLabel(CustomUserControl view, string value) + { + if (null != value) + { + view.Label = value; + } + else + { + view.ClearValue(CustomUserControl.LabelProperty); + } + } + + [ViewManagerProperty("color")] + public void SetColor(CustomUserControl view, Brush value) + { + if (null != value) + { + view.Foreground = value; + } + else + { + view.ClearValue(Control.ForegroundProperty); + } + } + + [ViewManagerProperty("backgroundColor")] + public void SetBackgroundColor(CustomUserControl view, Brush value) + { + if (null != value) + { + view.Background = value; + } + else + { + view.ClearValue(Control.BackgroundProperty); + } + } + + [ViewManagerCommand] + public void CustomCommand(CustomUserControl view, IReadOnlyList commandArgs) + { + // Execute command + } + } +} +``` + +### 2. Registering your View Manager + +As with native modules, we want to register our new `CustomUserControlViewManager` with React Native so we can actually use it. To do this, first we're going to create a `ReactPackageProvider` which implements [`Microsoft.ReactNative.IReactPackageProvider`](https://github.com/microsoft/react-native-windows/blob/main/vnext/Microsoft.ReactNative/IReactPackageProvider.idl). + +`ReactPackageProvider.cs`: + +```csharp +using Microsoft.ReactNative.Managed; + +namespace ViewManagerSample +{ + public partial class ReactPackageProvider : IReactPackageProvider + { + public void CreatePackage(IReactPackageBuilder packageBuilder) + { + CreatePackageImplementation(packageBuilder); + } + + /// + /// This method is implemented by the C# code generator + /// + partial void CreatePackageImplementation(IReactPackageBuilder packageBuilder); + } +} +``` + +Here we've implemented the `CreatePackage` method, which receives `packageBuilder` to build contents of the package. + +Now that we have the `ReactPackageProvider`, it's time to register it within our `ReactApplication`. We do that by simply adding the provider to the `PackageProviders` property. + +`App.xaml.cs`: + +```csharp +using Microsoft.ReactNative; + +namespace SampleApp +{ + sealed partial class App : ReactApplication + { + public App() + { + /* Other Init Code */ + + PackageProviders.Add(new Microsoft.ReactNative.Managed.ReactPackageProvider()); // Includes any modules in this project + PackageProviders.Add(new ViewManagerSample.ReactPackageProvider()); + + /* Other Init Code */ + } + } +} +``` + +This example assumes that the `ViewManagerSample.ReactPackageProvider` we created above is in a different project (assembly) than our application. However you'll notice that by default we also added a `Microsoft.ReactNative.Managed.ReactPackageProvider`. + +The `Microsoft.ReactNative.Managed.ReactPackageProvider` is a convenience that makes sure that all native modules and view managers defined within the app project automatically get registered. So if you're creating your view managers directly within the app project, you won't actually want to define a separate `ReactPackageProvider`. + +### More extensibility points + +- In some scenarios, a view manager might need to have more context at view creation time in order to decide what kind of control to instantiate. +This can be achieved by having the view manager implement the [`IViewManagerCreateWithProperties`](IViewManagerCreateWithProperties) interface. The `CreateViewWithProperties` method can then access the properties set in JSX by inspecting the `propertyMapReader`. + +```diff +-internal class CustomUserControlViewManager : AttributedViewManager { ++internal class CustomUserControlViewManager : AttributedViewManager, IViewManagerCreateWithProperties { +// rest of the view manager goes here... ++ // IViewManagerCreateWithProperties ++ public virtual object CreateViewWithProperties(Microsoft.ReactNative.IJSValueReader propertyMapReader) { ++ propertyMapReader.ReaderValue(out IDictionary propertyMap); ++ // create a XAML FrameworkElement based on properties in propertyMap ++ if (propertyMap.ContainsKey("foo)) { ++ return new Button(); ++ } else { ++ return new TextBox(); ++ } ++ } +} ++} +``` + +- Your view manager is also able to declare that it wants to be responsible for its own sizing and layout. +This is useful in scenarios where you are wrapping a native XAML control. To do so, implement the `Microsoft.ReactNative.IViewManagerRequiresNativeLayout` interface: + +```diff +-internal class CustomUserControlViewManager : AttributedViewManager { ++internal class CustomUserControlViewManager : AttributedViewManager, IViewManagerRequiresNativeLayout { +// rest of the view manager goes here... ++ // IViewManagerRequiresNativeLayout ++ virtual bool RequiresNativeLayout() { return true; } +``` + + +For this sample, assume we already have the `CustomUserControl` defined in the C# example. + +### 1. Authoring your View Manager + +Here is a sample view manager written in C++ called `CustomUserControlViewManager`. + +`CustomUserControlViewManager.h`: + +```cpp +#pragma once + +#include "pch.h" + +#include "winrt/Microsoft.ReactNative.h" + +namespace winrt::ViewManagerSample::implementation { + +struct CustomUserControlViewManager : winrt::implements< + CustomUserControlViewManager, + winrt::Microsoft::ReactNative::IViewManager, + winrt::Microsoft::ReactNative::IViewManagerWithNativeProperties, + winrt::Microsoft::ReactNative::IViewManagerWithCommands, + winrt::Microsoft::ReactNative::IViewManagerWithExportedEventTypeConstants, + winrt::Microsoft::ReactNative::IViewManagerWithReactContext> { + public: + CustomUserControlViewManager() = default; + + // IViewManager + winrt::hstring Name() noexcept; + + winrt::Windows::UI::Xaml::FrameworkElement CreateView() noexcept; + + // IViewManagerWithNativeProperties + winrt::Windows::Foundation::Collections:: + IMapView + NativeProps() noexcept; + + void UpdateProperties( + winrt::Windows::UI::Xaml::FrameworkElement const &view, + winrt::Microsoft::ReactNative::IJSValueReader const &propertyMapReader) noexcept; + + // IViewManagerWithCommands + winrt::Windows::Foundation::Collections::IVectorView Commands() noexcept; + + void DispatchCommand( + winrt::Windows::UI::Xaml::FrameworkElement const &view, + winrt::hstring const &commandId, + winrt::Microsoft::ReactNative::IJSValueReader const &commandArgsReader) noexcept; + + // IViewManagerWithExportedEventTypeConstants + winrt::Microsoft::ReactNative::ConstantProviderDelegate ExportedCustomBubblingEventTypeConstants() noexcept; + + winrt::Microsoft::ReactNative::ConstantProviderDelegate ExportedCustomDirectEventTypeConstants() noexcept; + + // IViewManagerWithReactContext + winrt::Microsoft::ReactNative::IReactContext ReactContext() noexcept; + + void ReactContext(winrt::Microsoft::ReactNative::IReactContext reactContext) noexcept; + +private: + winrt::Microsoft::ReactNative::IReactContext m_reactContext{ nullptr }; +}; + +} +``` + +`CustomUserControlViewManager.cpp`: + +```cpp +#include "pch.h" +#include "CustomUserControlViewManager.h" + +#include "JSValueReader.h" +#include "JSValueXaml.h" +#include "NativeModules.h" + +using namespace winrt; +using namespace Microsoft::ReactNative; +using namespace Windows::Foundation; +using namespace Windows::Foundation::Collections; + +using namespace Windows::UI::Xaml; +using namespace Windows::UI::Xaml::Media; +using namespace Windows::UI::Xaml::Controls; + +namespace winrt::ViewManagerSample::implementation { + +// IViewManager +hstring CustomUserControlViewManager::Name() noexcept { + return L"CustomUserControl"; +} + +FrameworkElement CustomUserControlViewManager::CreateView() noexcept { + return winrt::ViewManagerSample::CustomUserControl(); +} + +// IViewManagerWithNativeProperties +IMapView CustomUserControlViewManager::NativeProps() noexcept { + auto nativeProps = winrt::single_threaded_map(); + + nativeProps.Insert(L"label", ViewManagerPropertyType::String); + nativeProps.Insert(L"color", ViewManagerPropertyType::Color); + nativeProps.Insert(L"backgroundColor", ViewManagerPropertyType::Color); + + return nativeProps.GetView(); +} + +void CustomUserControlViewManager::UpdateProperties( + FrameworkElement const &view, + IJSValueReader const &propertyMapReader) noexcept { + if (auto control = view.try_as()) { + + const JSValueObject &propertyMap = JSValue::ReadObjectFrom(propertyMapReader); + + for (auto const &pair : propertyMap) { + auto const &propertyName = pair.first; + auto const &propertyValue = pair.second; + + if (propertyName == "label") { + if (propertyValue != nullptr) { + auto const &value = winrt::box_value(winrt::to_hstring(propertyValue.String())); + control.Label(value); + } else { + control.ClearValue(winrt::ViewManagerSample::CustomUserControl::LabelProperty()); + } + } else if (propertyName == "color") { + if (auto value = propertyValue.To()) { + control.Foreground(value); + } else { + control.ClearValue(Control::ForegroundProperty()); + } + } else if (propertyName == "backgroundColor") { + if (auto value = propertyValue.To()) { + control.Background(value); + } else { + control.ClearValue(Control::BackgroundProperty()); + } + } + } + } +} + +// IViewManagerWithCommands +IVectorView CustomUserControlViewManager::Commands() noexcept { + auto commands = winrt::single_threaded_vector(); + commands.Append(L"CustomCommand"); + return commands.GetView(); +} + +void CustomUserControlViewManager::DispatchCommand( + FrameworkElement const &view, + winrt::hstring const &commandId, + winrt::Microsoft::ReactNative::IJSValueReader const &commandArgsReader) noexcept { + if (auto control = view.try_as()) { + if (commandId == L"CustomCommand") { + const JSValueArray &commandArgs = JSValue::ReadArrayFrom(commandArgsReader); + // Execute command + } + } +} + +// IViewManagerWithExportedEventTypeConstants +ConstantProviderDelegate CustomUserControlViewManager::ExportedCustomBubblingEventTypeConstants() noexcept { + return [](winrt::Microsoft::ReactNative::IJSValueWriter const& constantWriter) { + // use constantWriter to define bubbling events, see ExportedCustomDirectEventTypeConstants + } +} + +ConstantProviderDelegate CustomUserControlViewManager::ExportedCustomDirectEventTypeConstants() noexcept { + return [](winrt::Microsoft::ReactNative::IJSValueWriter const& constantWriter) { + constantWriter.WritePropertyName(L"topMyEvent"); + constantWriter.WriteObjectBegin(); + WriteProperty(constantWriter, L"registrationName", L"onMyEvent"); + constantWriter.WriteObjectEnd(); + }; +} + +// IViewManagerWithReactContext +IReactContext CustomUserControlViewManager::ReactContext() noexcept { + return m_reactContext; +} + +void CustomUserControlViewManager::ReactContext(IReactContext reactContext) noexcept { + m_reactContext = reactContext; +} + +} +``` + + +### More extensibility points + +- In some scenarios, a view manager might need to have more context at view creation time in order to decide what kind of control to instantiate. +This can be achieved by having the view manager implement the [`IViewManagerCreateWithProperties`](IViewManagerCreateWithProperties) interface: +```diff +struct CustomUserControlViewManager : winrt::implements< + CustomUserControlViewManager, + winrt::Microsoft::ReactNative::IViewManager, + winrt::Microsoft::ReactNative::IViewManagerWithNativeProperties, + winrt::Microsoft::ReactNative::IViewManagerWithCommands, + winrt::Microsoft::ReactNative::IViewManagerWithExportedEventTypeConstants, ++ winrt::Microsoft::ReactNative::IViewManagerCreateWithProperties, + winrt::Microsoft::ReactNative::IViewManagerWithReactContext> { ++ // IViewManagerCreateWithProperties ++ winrt::Windows::Foundation::IInspectable CreateViewWithProperties(winrt::Microsoft::ReactNative::IJSValueReader const &propertyMapReader); +``` +The `CreateViewWithProperties` method can then access the properties set in JSX by inspecting the `propertyMapReader` just like it is done in the `UpdateProperties` method. + + +- Your view manager is also able to declare that it wants to be responsible for its own sizing and layout. This is useful in scenarios where you are wrapping a native XAML control. To do so, implement the `winrt::Microsoft::ReactNative::IViewManagerRequiresNativeLayout` interface: + +```diff +struct CustomUserControlViewManager : winrt::implements< + CustomUserControlViewManager, + winrt::Microsoft::ReactNative::IViewManager, + winrt::Microsoft::ReactNative::IViewManagerWithNativeProperties, + winrt::Microsoft::ReactNative::IViewManagerWithCommands, + winrt::Microsoft::ReactNative::IViewManagerWithExportedEventTypeConstants, ++ winrt::Microsoft::ReactNative::IViewManagerRequiresNativeLayout, + winrt::Microsoft::ReactNative::IViewManagerWithReactContext> { ++ // IViewManagerRequiresNativeLayout ++ bool RequiresNativeLayout() { return true; } +``` + + +### 2. Registering your View Manager + +As with native modules, we want to register our new `CustomUserControlViewManager` with React Native so we can actually use it. To do this, first we're going to create a `ReactPackageProvider` which implements [`Microsoft.ReactNative.IReactPackageProvider`](https://github.com/microsoft/react-native-windows/blob/main/vnext/Microsoft.ReactNative/IReactPackageProvider.idl). + +`ReactPackageProvider.idl`: + +```cpp +namespace ViewManagerSample +{ + [webhosthidden] + [default_interface] + runtimeclass ReactPackageProvider : Microsoft.ReactNative.IReactPackageProvider + { + ReactPackageProvider(); + }; +} +``` + +After that we add the .h and .cpp files: + +`ReactPackageProvider.h`: + +```cpp +#pragma once + +#include "ReactPackageProvider.g.h" + +using namespace winrt::Microsoft::ReactNative; + +namespace winrt::ViewManagerSample::implementation +{ + struct ReactPackageProvider : ReactPackageProviderT + { + ReactPackageProvider() = default; + + void CreatePackage(IReactPackageBuilder const& packageBuilder) noexcept; + }; +} + +namespace winrt::ViewManagerSample::factory_implementation +{ + struct ReactPackageProvider : ReactPackageProviderT {}; +} +``` + +`ReactPackageProvider.cpp`: + +```cpp +#include "pch.h" +#include "ReactPackageProvider.h" +#include "ReactPackageProvider.g.cpp" + +#include + +// NOTE: You must include the headers of your native modules here in +// order for the AddAttributedModules call below to find them. +#include "CustomUserControlViewManager.h" + +using namespace winrt::Microsoft::ReactNative; + +namespace winrt::ViewManagerSample::implementation { + +void ReactPackageProvider::CreatePackage(IReactPackageBuilder const& packageBuilder) +noexcept { + packageBuilder.AddViewManager( + L"CustomUserControlViewManager", []() { return winrt::make(); }); +} + +} // namespace winrt::ViewManagerSample::implementation +``` + +Here we've implemented the `CreatePackage` method, which receives `packageBuilder` to build contents of the package. And then we call `AddViewManager` with the name of our view manager and a lambda which returns an instance of the view manager. + +Now that we have the `ReactPackageProvider`, it's time to register it within our `ReactApplication`. We do that by simply adding the provider to the `PackageProviders` property. + +`App.cpp`: + +```cpp +#include "pch.h" + +#include "App.h" +#include "ReactPackageProvider.h" + +#include "winrt/ViewManagerSample.h" + +namespace winrt::SampleApp::implementation { + +App::App() noexcept { + /* Other Init Code */ + + PackageProviders().Append(make()); // Includes all modules in this project + PackageProviders().Append(winrt::ViewManagerSample::ReactPackageProvider()); + + /* Other Init Code */ +} + +} // namespace winrt::SampleApp::implementation +``` + +This example assumes that the `ViewManagerSample::ReactPackageProvider` we created above is in a different project (assembly) than our application. However you'll notice that by default we also added a `SampleApp::ReactPackageProvider`. + +The `SampleApp::ReactPackageProvider` is a convenience that makes sure that all native modules and view managers defined within the app project automatically get registered. So if you're creating your native modules directly within the app project, you won't actually want to define a separate `ReactPackageProvider`. + + + +### 3. Using your View Manager in JSX + +`ViewManagerSample.js`: + +```js +import React, { Component } from 'react'; +import { + AppRegistry, + Button, + requireNativeComponent, + StyleSheet, + UIManager, + View, +} from 'react-native'; + +let CustomUserControl = requireNativeComponent('CustomUserControl'); + +class ViewManagerSample extends Component { + onPress() { + if (_customControlRef) { + const tag = findNodeHandle(this._customControlRef); + UIManager.dispatchViewManagerCommand(tag, + UIManager.getViewManagerConfig('CustomUserControl').Commands.CustomCommand, + ['arg1', 'arg2']); + } + } + + render() { + return ( + + { this._customControlRef = ref; }} /> +