I need to create a native module just for my app, But I'm not able to do it #12092
-
Hey ! I need to create a native module for my app ( I'm not looking for distributing the module ), but I'm not able to understand the documentation. I have read it too many times and I'm just not enable to do it. The reason could be that i have never used React Native before. But if someone can please explain how to do a native module that just return a constant like 1 for example it would be of really help. The documentation that I have followed untill now are this one, I'm just following this three steps for Referencing Windows APIs within a React Native for Windows app project. It shoulf be different if i don't want to use WinRT API's ? |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 9 replies
-
This process is a bit more robust, as it involves creating a distributable library to add your native module. You can learn more at https://github.com/microsoft/react-native-windows-samples/tree/main/samples/NativeModuleSample. If you want to create just a native module for your app, you can simply follow this documentation: https://microsoft.github.io/react-native-windows/docs/native-modules. You can find more information about the available types here: https://microsoft.github.io/react-native-windows/docs/native-modules-jsvalue. Example
#pragma once
#include "pch.h"
using namespace winrt;
REACT_MODULE(MyNativeModule);
struct MyNativeModule
{
REACT_METHOD(Add, L"add");
double Add(double a, double b) noexcept
{
double result = a + b;
return result;
}
};
import { NativeModules } from "react-native"
const { MyNativeModule } = NativeModules;
const result = await MyNativeModule.add(20, 40);
console.log(result) // 60 And Voilà, it works perfectly😄. |
Beta Was this translation helpful? Give feedback.
-
And the other steps are not required too ? |
Beta Was this translation helpful? Give feedback.
-
Hey ! I just tried again with the first solution and it worked ! Thanks @Victor0814gui , you just saved me ! |
Beta Was this translation helpful? Give feedback.
-
You're welcome! I'm glad it worked, and I could help😆. |
Beta Was this translation helpful? Give feedback.
-
Hey @Victor0814gui ! Sorry for bothering so much, but for C# I can follow the same steps ? Or I will have to include it in a diferent package provider? |
Beta Was this translation helpful? Give feedback.
For the example mentioned above, yes. However, since the previous steps didn't work, I decided to write a simple example using Turbo Modules. I think it will be easier to test this way. I added the module with the name Estudies.h 😅 inside the projectName/windows/reactnativewindows/Modules/Estudies.h folder. You can find it here: https://github.com/Victor0814gui/simples-native-module/tree/main.