### Navigate to Project Directory Source: https://microsoft.github.io/react-native-windows/docs/getting-started Changes the current directory to the newly created React Native project folder. This is a standard command-line operation required before proceeding with project setup. ```bash cd ``` -------------------------------- ### Run React Native Windows App Source: https://microsoft.github.io/react-native-windows/docs/getting-started Starts the React Native Windows application without using Visual Studio. This command launches the Metro bundler and builds the Windows app. ```bash npx react-native run-windows ``` -------------------------------- ### Run Example App for React Native Windows Source: https://microsoft.github.io/react-native-windows/docs/native-platform-using Provides the command to run the example application for React Native Windows. This command is used to verify the end-to-end functionality of the native components. Ensure you are in the correct directory or use the specified alternative command. ```bash yarn react-native run-windows ``` -------------------------------- ### Create New React Native Project Source: https://microsoft.github.io/react-native-windows/docs/getting-started Initializes a new React Native project with a specified version. This command uses the React Native CLI to scaffold a new project directory. ```bash npx --yes @react-native-community/cli@latest init --version "^0.81.0" ``` -------------------------------- ### Initialize React Native Windows Native Code Source: https://microsoft.github.io/react-native-windows/docs/getting-started Initializes the native Windows code and projects for your React Native application. This command sets up the necessary Windows-specific configurations. ```bash npx react-native init-windows --overwrite ``` -------------------------------- ### Install React Native Windows Dependencies (PowerShell) Source: https://microsoft.github.io/react-native-windows/docs/rnw-dependencies Installs necessary development dependencies for React Native for Windows using a PowerShell script. This script requires an elevated PowerShell window to execute. It downloads and runs a script from a provided URL to set up the environment. ```powershell Set-ExecutionPolicy Unrestricted -Scope Process -Force; iex (New-Object System.Net.WebClient).DownloadString('https://aka.ms/rnw-vs2022-deps.ps1'); ``` -------------------------------- ### Install Node.js LTS (WinGet) Source: https://microsoft.github.io/react-native-windows/docs/rnw-dependencies Installs the Long-Term Support (LTS) version of Node.js using the Windows Package Manager (WinGet). This command should be run from an elevated Command Prompt. It specifically installs version 18.18.0. ```bash winget install OpenJS.NodeJS.LTS --version 18.18.0 ``` -------------------------------- ### Example react-native.config.js for App Project Source: https://microsoft.github.io/react-native-windows/docs/config An example JavaScript configuration file (`react-native.config.js`) demonstrating how to manually specify the Windows project configuration for an app. This is useful for overriding the default auto-linking behavior when the `react-native config` command doesn't correctly identify project details. ```javascript module.exports = { project: { windows: { sourceDir: 'windows', solutionFile: 'MyApp.sln', project: { projectFile: 'MyApp\/MyApp.vcxproj' } } } }; ``` -------------------------------- ### Setup GitHub Actions CI Pipeline for RNW App Source: https://microsoft.github.io/react-native-windows/docs/setup-ci This YAML configuration sets up a GitHub Actions workflow for a React Native for Windows application. It checks out the code, sets up Node.js and MSBuild, installs dependencies, and runs the Windows x64 release build with logging. This workflow is triggered on pull requests. ```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 - name: Run Windows x64 release run: npx react-native run-windows --arch x64 --release --logging ``` -------------------------------- ### Example react-native.config.js for MyModule Source: https://microsoft.github.io/react-native-windows/docs/config This code snippet shows an example of a `react-native.config.js` file for a React Native Windows module named 'MyModule'. It specifies the Windows platform configuration, including the source directory, solution file, and project details. ```javascript module.exports = { dependency: { platforms: { windows: { sourceDir: 'windows', solutionFile: 'MyModule.sln', projects: [ { projectFile: 'MyModule\MyModule.vcxproj', directDependency: true, } ], }, }, }, }; ``` -------------------------------- ### Verify Platform Installation with React Native CLI Source: https://microsoft.github.io/react-native-windows/docs/metro-config-out-tree-platforms This command helps verify that the necessary platform (e.g., macOS or Windows) is correctly installed and integrated with the React Native CLI. The output should include `platforms.macos.npmPackageName` or `platforms.windows.npmPackageName` if the respective platform is set up. ```bash npx react-native config ``` -------------------------------- ### JSValue Initialization and Conversion in C++ Source: https://microsoft.github.io/react-native-windows/docs/native-modules-jsvalue Provides examples of initializing JSValue, JSValueArray, and JSValueObject in C++. It covers basic type assignments, array and object creation, and explicit conversions to JSValues, noting their immutability. ```cpp #include "JSValue.h" JSValue twelve = 12; // creates a JSValue that holds an integer JSValue str = "string"; // yep, this one is a String // a few other types. JSValue nul = nullptr; JSValue boolean = false; // Arrays can be initialized with JSValueArray. JSValueArray array = JSValueArray{ "array ", "of", 4, " elements" }; assert(array.size() == 4); JSValueArray emptyArray = JSValueArray{}; assert(emptyArray.size() == 0); // JSValueArrays can be explicitly converted to JSValues, however // like all JSValues they will be immutable. Accessing the contents // via the AsArray() method will return a const JSValueArray. JSValue array2 = std::move(array); assert(array2.AsArray().size() == 4); JSValue emptyArray2 = std::move(emptyArray); assert(emptyArray2.AsArray().size() == 0); // Maps from strings to JSValues are called objects. The // JSValueObject type is how you make an empty map from strings // to JSValues. JSValueObject map = JSValueObject{}; map["something"] = 12; map["another_something"] = map["something"].AsInt32() * 2; // JSValueObjects may be initialized this way JSValueObject map2 = JSValueObject { { "something", 12 }, { "another_something", 24 }, }; // Like JSValueArrays, JSValueObjects can also be explicitly // converted to JSValues, and likewise they will be immutable. // Accessing the contents via the AsObject() method will return // a const JSValueObject. JSValue map3 = std::move(map); assert(map3.AsObject().size() == 2); JSValue map4 = std::move(map2); assert(map4.AsObject().size() == 2); ``` -------------------------------- ### Add React Native Windows Dependency Source: https://microsoft.github.io/react-native-windows/docs/getting-started Installs the react-native-windows package as a project dependency using either Yarn or NPM. This step is crucial for enabling Windows support in your React Native project. ```bash yarn add react-native-windows@^0.81.0 ``` ```bash npm install --save react-native-windows@^0.81.0 ``` -------------------------------- ### Available Templates Source: https://microsoft.github.io/react-native-windows/docs/init-windows-cli Lists the available templates that can be used with the `--template` option for the `init-windows` command. ```APIDOC ## GET /react-native-windows/templates ### Description Retrieves a list of all available templates for the `init-windows` command, including their names and descriptions. ### Method GET ### Endpoint /react-native-windows/templates ### Parameters No parameters required for this endpoint. ### Response #### Success Response (200) - **templates** (array) - A list of available templates. - **template_id** (string) - The identifier for the template (e.g., `cpp-app`). - **name** (string) - The human-readable name of the template. - **description** (string) - A brief description of what the template provides. - **is_default** (boolean) - Indicates if this is the default template. - **is_legacy** (boolean) - Indicates if this is a legacy template. #### Response Example ```json { "templates": [ { "template_id": "cpp-app", "name": "React Native Windows Application (New Arch, WinAppSDK, C++)", "description": "A RNW app using RN's New Architecture, built in C++ and targeting WinAppSDK", "is_default": true, "is_legacy": false }, { "template_id": "cpp-lib", "name": "React Native Windows Library (C++)", "description": "A RNW (Turbo) Native Module supporting RN's New and Old Architectures built in C++", "is_default": false, "is_legacy": false }, { "template_id": "old/uwp-cpp-app", "name": "React Native Windows Application (Old Arch, UWP, C++)", "description": "A RNW app using RN's Old Architecture, built in C++ and targeting UWP", "is_default": false, "is_legacy": true }, { "template_id": "old/uwp-cs-app", "name": "React Native Windows Application (Old Arch, UWP, C#)", "description": "A RNW app using RN's Old Architecture, built in C# and targeting UWP", "is_default": false, "is_legacy": true } ] } ``` ``` -------------------------------- ### Implementing IViewManagerCreateWithProperties (C++/WinRT) Source: https://microsoft.github.io/react-native-windows/docs/view-managers Extends a view manager to implement IViewManagerCreateWithProperties, enabling view creation with initial properties. The CreateViewWithProperties method receives a property map reader to access these properties. ```cpp 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); }; ``` -------------------------------- ### VS Code Debug Configuration for React Native Windows Source: https://microsoft.github.io/react-native-windows/docs/getting-started Configuration file for VS Code to launch and debug React Native for Windows applications. This JSON defines the debugger settings. ```json { "version": "0.2.0", "configurations": [ { "name": "Debug Windows", "cwd": "${workspaceFolder}", "type": "reactnative", "request": "launch", "platform": "windows" } ] } ``` -------------------------------- ### ReactRootView Class Documentation Source: https://microsoft.github.io/react-native-windows/docs/ReactRootView Documentation for the ReactRootView class, its properties, constructors, and methods. ```APIDOC ## ReactRootView ### Description A XAML component that hosts React Native UI elements. ### Kind `class` ### Extends `Grid` ### Implements `IReactRootViewExperimental` ### Properties #### ComponentName - **ComponentName** (string) - The name of the root UI component registered in JavaScript with help of the `AppRegistry.registerComponent` method. #### ExperimentalUseFabric - **ExperimentalUseFabric** (bool) - EXPERIMENTAL: Use Fabric for this ReactRootView. #### InitialProps - **InitialProps** (JSValueArgWriter) - The `JSValueArgWriter` that is used to serialize the main component initial properties. #### IsPerspectiveEnabled - **IsPerspectiveEnabled** (bool) - Default value: `true`. XAML's default projection in 3D is orthographic (all lines are parallel) However React Native's default projection is a one-point perspective. This property enables setting a default perspective projection on the main control to mimic this. #### ReactNativeHost - **ReactNativeHost** (ReactNativeHost) - The `ReactNativeHost` associated with the `ReactRootView`. It must be set to show any React UI elements. ### Constructors #### ReactRootView - **`ReactRootView`**() ### Methods #### ReloadView - **`ReloadView`**() - Reloads the current `ReactRootView` UI components. ### Last updated 5/4/2021 ``` -------------------------------- ### Initialize Native Windows Code for Library Project Source: https://microsoft.github.io/react-native-windows/docs/native-modules-setup This command initializes the native Windows code for a library project using the C++/WinRT template. It sets up the necessary files and structure for a native Windows library within a React Native project. ```bash npx @react-native-community/cli init-windows --template cpp-lib --overwrite ``` -------------------------------- ### Initialize React Native Windows Project Source: https://microsoft.github.io/react-native-windows/docs/init-windows-cli This command initializes a new React Native for Windows project using the default template. It sets up the necessary files and configurations for a Windows-specific React Native application. ```bash npx react-native init-windows ``` -------------------------------- ### ReactNativeHost Class (New Architecture) Source: https://microsoft.github.io/react-native-windows/docs/native-api/ReactNativeHost The main entry-point to create and manage a React instance with the new architecture. It allows configuration via ReactInstanceSettings and control over instance loading. ```APIDOC ## ReactNativeHost (New Architecture) ### Description This class is the main entry-point to create a React instance for the new architecture. It configures the instance using `ReactInstanceSettings` and controls when to load the instance. Use `ReactInstanceSettings` events to observe instance creation, loading, and destruction. ### Properties #### InstanceSettings - **InstanceSettings** (`ReactInstanceSettings`) - Provides access to this host's `ReactInstanceSettings` to configure the react instance. #### PackageProviders - **PackageProviders** (`readonly IVector`) - Provides access to the list of `IReactPackageProvider`'s that the React instance will use to provide native modules to the application. This can be used to register additional package providers, such as package providers from community modules or other shared libraries. ### Constructors #### ReactNativeHost - **`ReactNativeHost`**() ### Methods #### FromContext - **`static ReactNativeHost FromContext`**(`IReactContext reactContext`) - Description: Returns the `ReactNativeHost` instance associated with the given `IReactContext`. #### LoadInstance - **`IAsyncAction LoadInstance`**() - Description: Loads a new React instance. It is an alias for the `ReloadInstance` method. #### ReloadInstance - **`IAsyncAction ReloadInstance`**() - Description: Unloads the current React instance and loads a new one. This process involves creating a JavaScript engine instance and launching the provided JavaScript code bundle. If a React instance is already running, `ReloadInstance` shuts it down before loading the new one. The React instance lifecycle can be observed via `ReactInstanceSettings.InstanceCreated`, `ReactInstanceSettings.InstanceLoaded`, and `ReactInstanceSettings.InstanceDestroyed` events. #### UnloadInstance - **`IAsyncAction UnloadInstance`**() - Description: Unloads the current React instance. After unloading, all React resources, including the JavaScript engine environment, are cleaned up. The React instance destruction can be observed with the `ReactInstanceSettings.InstanceDestroyed` event. ### Referenced by - `IReactViewHost` - `ReactCoreInjection` - `ReactNativeWin32App` - `RedBoxHelper` ``` -------------------------------- ### React Instance Settings Constructor Source: https://microsoft.github.io/react-native-windows/docs/native-api/ReactInstanceSettings Initializes a new instance of the ReactInstanceSettings class. ```csharp ReactInstanceSettings() ``` -------------------------------- ### Implement Asynchronous HTTP GET Request in C# Source: https://microsoft.github.io/react-native-windows/docs/native-modules-async This snippet provides the implementation logic for the `GetHttpResponseAsync` method. It utilizes `HttpClient` to asynchronously send a GET request to a specified URI, reads the response content, and returns it as a string. Error handling for the HTTP request itself is not included in this basic implementation. ```csharp // Create an HttpClient object var httpClient = new HttpClient(); // Send the GET request asynchronously var httpResponseMessage = await httpClient.GetAsync(new Uri(uri)); var content = await httpResponseMessage.Content.ReadAsStringAsync(); return content; ``` -------------------------------- ### ReactNativeHost Class (Old Architecture) Source: https://microsoft.github.io/react-native-windows/docs/native-api/ReactNativeHost The main entry-point to create and manage a React instance with the old architecture. It allows configuration via ReactInstanceSettings and control over instance loading. ```APIDOC ## ReactNativeHost (Old Architecture) ### Description This class is the main entry-point to create a React instance for the old architecture. It configures the instance using `ReactInstanceSettings` and controls when to load the instance. Use `ReactInstanceSettings` events to observe instance creation, loading, and destruction. ### Properties #### InstanceSettings - **InstanceSettings** (`ReactInstanceSettings`) - Provides access to this host's `ReactInstanceSettings` to configure the react instance. #### PackageProviders - **PackageProviders** (`readonly IVector`) - Provides access to the list of `IReactPackageProvider`'s that the React instance will use to provide native modules to the application. This can be used to register additional package providers, such as package providers from community modules or other shared libraries. ### Constructors #### ReactNativeHost - **`ReactNativeHost`**() ### Methods #### FromContext - **`static ReactNativeHost FromContext`**(`IReactContext reactContext`) - Description: Returns the `ReactNativeHost` instance associated with the given `IReactContext`. #### LoadInstance - **`IAsyncAction LoadInstance`**() - Description: Loads a new React instance. It is an alias for the `ReloadInstance` method. #### ReloadInstance - **`IAsyncAction ReloadInstance`**() - Description: Unloads the current React instance and loads a new one. This process involves creating a JavaScript engine instance and launching the provided JavaScript code bundle. If a React instance is already running, `ReloadInstance` shuts it down before loading the new one. The React instance lifecycle can be observed via `ReactInstanceSettings.InstanceCreated`, `ReactInstanceSettings.InstanceLoaded`, and `ReactInstanceSettings.InstanceDestroyed` events. #### UnloadInstance - **`IAsyncAction UnloadInstance`**() - Description: Unloads the current React instance. After unloading, all React resources, including the JavaScript engine environment, are cleaned up. The React instance destruction can be observed with the `ReactInstanceSettings.InstanceDestroyed` event. ``` -------------------------------- ### EmitEventSetterDelegate Source: https://microsoft.github.io/react-native-windows/docs/native-api/EmitEventSetterDelegate The EmitEventSetterDelegate is a delegate used to get arguments for an event emission on an EventEmitter in React Native for Windows. ```APIDOC ## EmitEventSetterDelegate ### Description A delegate that gets the arguments for an event emit on an EventEmitter. ### Kind `delegate` ### Methods #### Invoke `void Invoke(JSValueArgWriter argWriter)` ### Referenced by * `EventEmitterInitializerDelegate` ``` -------------------------------- ### Launching FileOpenPicker with UIDispatcher (C++/WinRT) Source: https://microsoft.github.io/react-native-windows/docs/native-modules-async Shows how to correctly launch a FileOpenPicker using UIDispatcher.Post in a C++/WinRT native module. This ensures the operation runs on the UI thread, resolving issues with invalid window handles. ```cpp REACT_METHOD(OpenFile, L"openFile"); void OpenFile() noexcept { context.UIDispatcher().Post([]()->winrt::fire_and_forget { winrt::Windows::Storage::Pickers::FileOpenPicker openPicker; // Other initialization code winrt::Windows::Storage::StorageFile file = co_await openPicker.PickSingleFileAsync(); if (file != nullptr) { // File opened successfully } else { // Error while opening the file } }); } ``` -------------------------------- ### Get XamlUIService from IReactContext in C++ Source: https://microsoft.github.io/react-native-windows/docs/XamlUIService A static method to obtain the XamlUIService instance associated with a given IReactContext. This is the primary way to access the service. ```cpp static XamlUIService^ XamlUIService::FromContext(IReactContext^ context) { // Implementation details for getting service from context return nullptr; } ``` -------------------------------- ### Implementing ReactPackageProvider Interface (C++/WinRT) Source: https://microsoft.github.io/react-native-windows/docs/view-managers This C++/WinRT code defines the ReactPackageProvider class, which implements the Microsoft.ReactNative.IReactPackageProvider interface. It includes the necessary header and the default constructor, preparing the class for package creation. ```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 {}; } ``` -------------------------------- ### Get XamlRoot Element in C++ Source: https://microsoft.github.io/react-native-windows/docs/XamlUIService Retrieves the default XamlRoot element for the application. This is necessary for certain APIs to function correctly, especially with XAML Islands. ```cpp static XamlRoot^ XamlUIService::GetXamlRoot(IReactPropertyBag^ properties) { // Implementation details for getting XamlRoot return nullptr; } ``` -------------------------------- ### IReactPropertyBag Interface Methods Source: https://microsoft.github.io/react-native-windows/docs/native-api/IReactPropertyBag This section details the methods available for interacting with the IReactPropertyBag interface, including copying properties, getting values, creating properties if they don't exist, and setting property values. ```APIDOC ## IReactPropertyBag Interface ### Description `IReactPropertyBag` provides a thread-safe property storage. Properties are identified by an instance of `IReactPropertyName`. It is expected that there will be no direct use of this interface. Ideally, all usage should happen through strongly-typed accessors. ### Methods #### CopyFrom ##### Description Copies the properties from another property bag. ##### Method `void CopyFrom(IReactPropertyBag other)` #### Get ##### Description Gets the value of the specified property name. Returns null if the property does not exist. ##### Method `Object Get(IReactPropertyName name)` #### GetOrCreate ##### Description Gets or creates the value of the specified property name. If the property exists, its value is returned. If it does not exist, a new property is created by calling the `createValue` delegate. The function may return null if `createValue` returns null. The `createValue` is called outside of any locks, and its result might not be used if another thread sets the property value before the created value is stored. ##### Method `Object GetOrCreate(IReactPropertyName name, ReactCreatePropertyValue createValue)` #### Set ##### Description Sets the specified property name to the given value. Returns the previously-stored property value, or null if the property did not exist. If the new value is null, the property is removed. ##### Method `Object Set(IReactPropertyName name, Object value)` ### Referenced by * `IReactContext` * `ReactCoreInjection` * `ReactInstanceSettings` * `ReactPropertyBagHelper` * `Timer` * `UIBatchCompleteCallback` * `XamlUIService` ``` -------------------------------- ### Get Default Accessible Root Element in C++ Source: https://microsoft.github.io/react-native-windows/docs/XamlUIService Retrieves the default FrameworkElement used for accessibility purposes, such as announcing UI elements. It takes IReactPropertyBag as input. ```cpp static FrameworkElement^ XamlUIService::GetAccessibleRoot(IReactPropertyBag^ properties) { // Implementation details for getting accessible root return nullptr; } ``` -------------------------------- ### ComponentIslandComponentViewInitializer Source: https://microsoft.github.io/react-native-windows/docs/native-api/ComponentIslandComponentViewInitializer Details the ComponentIslandComponentViewInitializer delegate, including its experimental nature and the Invoke method signature. ```APIDOC ## Delegate: ComponentIslandComponentViewInitializer ### Description This is an experimental delegate used for initializing component views in React Native for Windows. ### Method `Invoke` ### Signature `void Invoke(ContentIslandComponentView view)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ### Referenced by * `IReactCompositionViewComponentBuilder` ``` -------------------------------- ### ReactNativeHost Class Overview Source: https://microsoft.github.io/react-native-windows/docs/ReactNativeHost Overview of the ReactNativeHost class, its purpose, and key components. ```APIDOC ## ReactNativeHost ### Description This is the main entry-point to create a React instance. The `ReactNativeHost` object exists to configure the instance using `ReactInstanceSettings` before it is loaded, as well as enabling control of when to load the instance. Use `ReactInstanceSettings` events to observe instance creation, loading, and destruction. ### Properties - **InstanceSettings** (`ReactInstanceSettings`) - Provides access to this host's `ReactInstanceSettings` to configure the react instance. - **PackageProviders** (`readonly` `IVector`<`IReactPackageProvider`>) - Provides access to the list of `IReactPackageProvider`'s that the React instance will use to provide native modules to the application. This can be used to register additional package providers, such as package providers from community modules or other shared libraries. ### Constructors - **`ReactNativeHost`**() ### Methods - **`FromContext`** (`static` `ReactNativeHost` `FromContext`(`IReactContext` reactContext)) Returns the `ReactNativeHost` instance associated with the given `IReactContext`. - **`LoadInstance`** (`IAsyncAction` `LoadInstance`()) Loads a new React instance. It is an alias for `ReloadInstance` method. - **`ReloadInstance`** (`IAsyncAction` `ReloadInstance`()) Unloads the current React instance and loads a new one. The React instance loading creates an instance of the JavaScript engine, and launches the provided JavaScript code bundle. If a React instance is already running in this host, then `ReloadInstance` shuts down the already the running React instance, and loads a new React instance. The React instance lifecycle can be observed with the following events: * The `ReactInstanceSettings.InstanceCreated` event is raised when the React instance is just created. * The `ReactInstanceSettings.InstanceLoaded` event is raised when the React instance completed loading the JavaScript bundle. * The `ReactInstanceSettings.InstanceDestroyed` event is raised when the React instance is destroyed. - **`UnloadInstance`** (`IAsyncAction` `UnloadInstance`()) Unloads current React instance. After the React instance is unloaded, all the React resources including the JavaScript engine environment are cleaned up. The React instance destruction can be observed with the `ReactInstanceSettings.InstanceDestroyed` event. ``` -------------------------------- ### Get Top-Level Window ID (C++) Source: https://microsoft.github.io/react-native-windows/docs/native-api/ReactCoreInjection Retrieves the window handle (HWND) as a 64-bit unsigned integer for the currently active top-level application window. This is an experimental feature. ```cpp uint64_t GetTopLevelWindowId(IReactPropertyBag properties) ``` -------------------------------- ### Get XAML Island Window Handle in C++ Source: https://microsoft.github.io/react-native-windows/docs/XamlUIService Retrieves the window handle (HWND) of the XAML Island window for the current React instance. Returns a uint64_t representing the handle. ```cpp static uint64_t XamlUIService::GetIslandWindowHandle(IReactPropertyBag^ properties) { // Implementation details for getting island window handle return 0; } ``` -------------------------------- ### React Native init-windows Command Source: https://microsoft.github.io/react-native-windows/docs/init-windows-cli Initializes a new React Native for Windows project from a given template. This command can also be used to re-initialize an existing project. ```APIDOC ## POST /react-native-windows/init-windows ### Description Initializes a new React Native for Windows project from a given template. This command can also be used to re-initialize an existing project. ### Method POST ### Endpoint /react-native-windows/init-windows ### Parameters #### Query Parameters - **logging** (boolean) - Optional - Verbose output logging. - **template** (string) - Optional - Specify the template to use (default: `cpp-app`). - **name** (string) - Optional - The native project name. Defaults to the name property in `app.json` or `package.json`. - **namespace** (string) - Optional - The native project namespace, expressed using dots as separators, i.e. `Level1.Level2.Level3`. Defaults to the same as name. - **overwrite** (boolean) - Optional - Overwrite any existing files without prompting. - **no-telemetry** (boolean) - Optional - Disables sending telemetry that allows analysis of usage and failures of the react-native-windows CLI. - **list** (boolean) - Optional - Shows a list with all available templates with their descriptions. - **help** (boolean) - Optional - Display help for command. ### Request Example ```json { "command": "npx react-native init-windows", "options": { "template": "cpp-lib", "name": "MyAwesomeApp", "namespace": "com.example.myawesomeapp", "overwrite": true, "no-telemetry": true } } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating the project initialization status. - **details** (object) - Contains details about the initialization process, including saved configurations. - **name** (string) - The saved native project name. - **namespace** (string) - The saved native project namespace. - **template** (string) - The saved template used. #### Response Example ```json { "message": "React Native for Windows project initialized successfully.", "details": { "name": "MyAwesomeApp", "namespace": "com.example.myawesomeapp", "template": "cpp-lib" } } ``` ### Error Handling - **400 Bad Request**: Invalid options or parameters provided. - **500 Internal Server Error**: An unexpected error occurred during initialization. ``` -------------------------------- ### Get XAML Element from React Tag in C++ Source: https://microsoft.github.io/react-native-windows/docs/XamlUIService Retrieves the underlying XAML FrameworkElement associated with a given React tag. This is useful for direct manipulation or inspection of UI elements. ```cpp DependencyObject^ XamlUIService::ElementFromReactTag(int64_t reactTag) { // Implementation details for getting element from tag return nullptr; } ``` -------------------------------- ### Implement View Creation with Properties in C# Source: https://microsoft.github.io/react-native-windows/docs/view-managers Allows a view manager to create a native control based on properties provided during view instantiation. The CreateViewWithProperties method inspects the propertyMapReader to determine which control to instantiate. ```csharp 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(); } } } ``` -------------------------------- ### Accessing UI Dispatcher with IReactContext Source: https://microsoft.github.io/react-native-windows/docs/IReactContext Demonstrates how to access the `UIDispatcher` property of the `IReactContext` interface to get the dispatcher for the UI thread. This enables posting asynchronous work to the UI thread. ```csharp IReactDispatcher UIDispatcher { get; } // Usage example: // UIDispatcher.Post(() => { /* UI update code */ }); ``` -------------------------------- ### Initializing ReactContext with UIDispatcher (C++/WinRT) Source: https://microsoft.github.io/react-native-windows/docs/native-modules-async Illustrates how to initialize the ReactContext, which provides access to the UIDispatcher, in a C++/WinRT native module using the REACT_INIT attribute. This context is necessary for calling UIDispatcher.Post. ```cpp REACT_INIT(Initialize); void Initialize(const winrt::Microsoft::ReactNative::ReactContext& reactContext) noexcept { context = reactContext; } ``` -------------------------------- ### Example codegenConfig for React Native Windows Source: https://microsoft.github.io/react-native-windows/docs/codegen-windows-cli Demonstrates the configuration object for `codegen-windows` within a project's `package.json`. This configuration specifies settings for native module and component generation on Windows. ```json "codegenConfig": { "name": "NativeModuleSampleSpec", "type": "all", "jsSrcsDir": "src", "includesGeneratedCode": true, "windows": { "namespace": "NativeModuleSampleCodegen", "generators": [ "modulesWindows", "componentsWindows" ], "outputDirectory": "windows/NativeModuleSample/codegen", "separateDataTypes": true } } ``` -------------------------------- ### React Native Windows Configuration in package.json Source: https://microsoft.github.io/react-native-windows/docs/init-windows-cli This JSON snippet shows the configuration saved by the `init-windows` command within the `package.json` file. It stores the project name, namespace, and template used for initialization, allowing for consistent re-initialization. ```json { "react-native-windows": { "init-windows": { "name": "MyApp", "namespace": "MyApp", "template": "cpp-app" } } } ``` -------------------------------- ### Accessing JavaScript Dispatcher with IReactContext Source: https://microsoft.github.io/react-native-windows/docs/IReactContext Shows how to access the `JSDispatcher` property of the `IReactContext` interface to get the dispatcher for the JavaScript engine thread. This allows posting asynchronous work to the JavaScript thread. ```csharp IReactDispatcher JSDispatcher { get; } // Usage example: // JSDispatcher.Post(() => { /* JavaScript code */ }); ``` -------------------------------- ### Create Default RedBox Handler (C#) Source: https://microsoft.github.io/react-native-windows/docs/IRedBoxHandler Demonstrates how to create a default RedBox handler using RedBoxHelper in C#. This is a utility function to get the standard error reporting mechanism. ```csharp RedBoxHelper::CreateDefaultHandler(Host); ``` -------------------------------- ### Get Value at Index from JSI Array Source: https://microsoft.github.io/react-native-windows/docs/native-api/JsiRuntime Retrieves a JSI value reference from a JSI object array at a specified index. This is a core operation for accessing elements within JavaScript arrays. ```cpp JsiValueRef GetValueAtIndex( JsiObjectRef arr, uint32_t index ); > **EXPERIMENTAL** ``` -------------------------------- ### IReactViewHost (Old Architecture) Source: https://microsoft.github.io/react-native-windows/docs/native-api/IReactViewHost Interface for implementing a non-XAML platform ReactRootView using the Old Architecture. Provides methods for attaching, detaching, reloading, and unloading view instances. ```APIDOC ## IReactViewHost (Old Architecture) ### Description Used to implement a non-XAML platform ReactRootView. ### Properties #### ReactNativeHost `readonly` `ReactNativeHost` `ReactNativeHost` - The ReactNativeHost associated with this ReactViewHost. ### Methods #### AttachViewInstance `IAsyncAction` **`AttachViewInstance`**(`IReactViewInstance` operation) Attaches IReactViewInstance to the IReactViewHost. #### DetachViewInstance `IAsyncAction` **`DetachViewInstance`**() Detaches IReactViewInstance from the IReactViewHost. #### ReloadViewInstance `IAsyncAction` **`ReloadViewInstance`**() Reloads the IReactViewInstance if it is attached. #### ReloadViewInstanceWithOptions `IAsyncAction` **`ReloadViewInstanceWithOptions`**(`ReactViewOptions` operation) Reloads IReactViewInstance if it is attached with a new set of options. #### UnloadViewInstance `IAsyncAction` **`UnloadViewInstance`**() Unloads the attached IReactViewInstance. ``` -------------------------------- ### Get Property ID Array from JSI Object Source: https://microsoft.github.io/react-native-windows/docs/native-api/JsiRuntime Retrieves an array of property ID references for all enumerable properties of a JSI object. This function is useful for iterating over an object's properties. ```cpp JsiObjectRef GetPropertyIdArray( JsiObjectRef obj ); > **EXPERIMENTAL** ``` -------------------------------- ### IReactViewHost (New Architecture) Source: https://microsoft.github.io/react-native-windows/docs/native-api/IReactViewHost Interface for implementing a non-XAML platform ReactRootView using the New Architecture. Provides methods for attaching, detaching, reloading, and unloading view instances. ```APIDOC ## IReactViewHost (New Architecture) ### Description Used to implement a non-XAML platform ReactRootView. ### Properties #### ReactNativeHost `readonly` `ReactNativeHost` `ReactNativeHost` - The ReactNativeHost associated with this ReactViewHost. ### Methods #### AttachViewInstance `IAsyncAction` **`AttachViewInstance`**(`IReactViewInstance` operation) Attaches IReactViewInstance to the IReactViewHost. #### DetachViewInstance `IAsyncAction` **`DetachViewInstance`**() Detaches IReactViewInstance from the IReactViewHost. #### ReloadViewInstance `IAsyncAction` **`ReloadViewInstance`**() Reloads the IReactViewInstance if it is attached. #### ReloadViewInstanceWithOptions `IAsyncAction` **`ReloadViewInstanceWithOptions`**(`ReactViewOptions` operation) Reloads IReactViewInstance if it is attached with a new set of options. #### UnloadViewInstance `IAsyncAction` **`UnloadViewInstance`**() Unloads the attached IReactViewInstance. ``` -------------------------------- ### Add React Native Picker Dependency (Yarn) Source: https://microsoft.github.io/react-native-windows/docs/managing-cpp-deps Installs the React Native Picker module using Yarn. This is a common step when adding UI components that have native C++ dependencies. ```bash yarn add @react-native-picker/picker ``` -------------------------------- ### IReactViewHost Interface Methods Source: https://microsoft.github.io/react-native-windows/docs/IReactViewHost This section details the methods available on the IReactViewHost interface for managing React Native view instances. ```APIDOC ## IReactViewHost Interface ### Description Used to implement a non-XAML platform ReactRootView. This interface provides methods for managing the lifecycle of a React Native view instance. ### Methods #### AttachViewInstance ##### Description Attaches an `IReactViewInstance` to the `IReactViewHost`. ##### Method `IAsyncAction` ##### Endpoint N/A (Interface Method) ##### Parameters ###### Request Body - **operation** (`IReactViewInstance`) - Required - The React view instance to attach. #### DetachViewInstance ##### Description Detaches the `IReactViewInstance` from the `IReactViewHost`. ##### Method `IAsyncAction` ##### Endpoint N/A (Interface Method) #### ReloadViewInstance ##### Description Reloads the `IReactViewInstance` if it is currently attached. ##### Method `IAsyncAction` ##### Endpoint N/A (Interface Method) #### ReloadViewInstanceWithOptions ##### Description Reloads the `IReactViewInstance` if it is attached, using a new set of options. ##### Method `IAsyncAction` ##### Endpoint N/A (Interface Method) ##### Parameters ###### Request Body - **operation** (`ReactViewOptions`) - Required - The new options to use for reloading the view instance. #### UnloadViewInstance ##### Description Unloads the attached `IReactViewInstance`. ##### Method `IAsyncAction` ##### Endpoint N/A (Interface Method) ### Response #### Success Response (200) - **Result** (`void`) - Indicates the operation completed successfully. #### Response Example ```json { "Result": null } ``` ``` -------------------------------- ### Get React Root View (C# - Old Architecture) Source: https://microsoft.github.io/react-native-windows/docs/native-api/XamlUIService Obtains the ReactRootView for a given FrameworkElement. This is useful for navigating the React Native view hierarchy within the native code, particularly in the old architecture. ```csharp public ReactRootView GetReactRootView(FrameworkElement view) { // Implementation to get ReactRootView return null; // Placeholder } ``` -------------------------------- ### Build Solution with MSBuild after Restoring Packages Source: https://microsoft.github.io/react-native-windows/docs/managing-cpp-deps Command to restore and build a Visual Studio solution using MSBuild. This command assumes that PackageReference is the default restore style and will handle remaining dependencies. ```batch MSBuild.exe /restore your_solution.sln ``` -------------------------------- ### C# Native Module Initialization with Timer Source: https://microsoft.github.io/react-native-windows/docs/native-modules-advanced This snippet shows how to perform initialization logic in a C# native module using the [ReactInitializer] attribute. It includes setting up a periodic timer to execute a task every 5 seconds and cancelling the timer when the module is disposed. ```csharp [ReactModule] internal sealed class NativeModuleSample { private ThreadPoolTimer m_timer; [ReactInitializer] public void Initialize(ReactContext reactContext) { m_timer = ThreadPoolTimer.CreatePeriodicTimer( new TimerElapsedHandler((timer) => { // Do something every 5 seconds }), TimeSpan.FromSeconds(5) ); } ~NativeModuleSample() { _timer?.Cancel(); } } ``` -------------------------------- ### VS Code launch.json for Attaching to RNW Packager Source: https://microsoft.github.io/react-native-windows/docs/debugging-javascript Configuration for VS Code's launch.json file to attach to an already running React Native packager for debugging. This is useful when Metro is started separately. ```json { "name": "Attach to packager", "cwd": "${workspaceFolder}", "type": "reactnative", "request": "attach" } ``` -------------------------------- ### IViewManagerWithCommands Interface Source: https://microsoft.github.io/react-native-windows/docs/native-api/IViewManagerWithCommands Details about the IViewManagerWithCommands interface, its properties, and methods. ```APIDOC ## Interface: IViewManagerWithCommands ### Description Represents a view manager that supports commands in React Native for Windows. ### Properties #### Commands - **Commands** (IVectorView) - Readonly. A collection of available commands. ### Methods #### DispatchCommand - **`DispatchCommand`** - **Description**: Dispatches a command to a specific view. - **Method**: `void` - **Parameters**: - **view** (FrameworkElement) - Required - The target UI element. - **commandId** (string) - Required - The identifier of the command to dispatch. - **commandArgsReader** (IJSValueReader) - Required - An object to read command arguments. ### Last updated 6/6/2025 ```