microsoft / react-native-windows-samples

A repository showcasing React Native samples and templates for Windows, macOS, and Surface Duo.
https://microsoft.github.io/react-native-windows/
MIT License
486 stars 201 forks source link

Help: simple app with a C# native module #979

Open wuleninja opened 1 month ago

wuleninja commented 1 month ago

Suggestion

Hi,

First, thanks for these powerful tools that you've spent so much time developing for everyone!

I'm quite new to RN, and have a Windows desktop app to dev with it. But I haven't been able to get my hands on a simple RNW app that makes uses of a custom (developed in situ) C# native module.

I could find examples of RNW apps, or C# native modules separately, but not the complete example with both, that would show me where each type of file go, to replicate, or even run directly with "npx react-native run-windows".

Can someone please show me a working example?

Thanks again

Platforms

Android, iOS, Windows

Sample code

No response

jonthysell commented 1 month ago

You can easily create C# modules within your RNW Paper (UWP) C# application using the [ReactModule] tags.

C# Module Docs: https://microsoft.github.io/react-native-windows/docs/native-modules#3-authoring-your-native-module

Example of an in-line C# module definition within a sample app: https://github.com/microsoft/react-native-windows/blob/main/packages/sample-apps/windows/SampleAppCS/DebugConsole.cs

Example of that inline module being using in JS: https://github.com/microsoft/react-native-windows/blob/bc8039e64a43bb834436ff7466e5a6af52c7443f/packages/sample-apps/index.windows.js#L38

Note this example is for the Paper renderer, these is no example/support yet for Fabric.

wuleninja commented 1 month ago

Thank you very much for this answer!

I've tried to npx react-native run-windows inside this sample-apps project to see it working with my own eyes, but I couldn't get npm install to finish successfully. Are there some specific technical prerequisites that I'm missing? Like, can I use RNW (with Paper) v0.75+ or should I use like v0.73- or earlier?

Thanks again 🙇 🙏

wuleninja commented 1 month ago

I removed these dev dependencies from package.json:

"@rnw-scripts/babel-react-native-config": "0.0.0", "@rnw-scripts/metro-dev-config": "0.0.0", so that npm install finished.

Then, when trying a npx react-native run-windows, I get a lot of error messages about $HOME/vnext files missing. Is this something to install first?

wuleninja commented 1 month ago

@jonthysell in here: https://github.com/microsoft/react-native-windows/blob/bc8039e64a43bb834436ff7466e5a6af52c7443f/packages/sample-apps/index.windows.js#L38, isn't it the C++ version being used, not the C# one (since the TurboModuleRegistry is involved)?

wuleninja commented 1 month ago

Is the use of Visual Studio mandatory for the dev of native module to work?