Using TypeScript to access native functions in react-native

Recently, I found myself in need of a basic function to interact with native code. Rather than creating a package, I opted to create the Java files as if they were for a plugin and registered them in MainApplication.

As I'm using TypeScript, I am currently facing challenges with RN to Java interaction. I attempted to do so with a JS file like this:

import NativeModules from 'react-native';
const AndroidService = NativeModules;
export default { AndroidService }

However, I then encountered the need to define types (prompted by VS Code):

Property 'play' does not exist on type '{ AndroidService: typeof import("/home/karol/Git/TailosiveHub-react/node_modules/@types/react-native/index"); }'.

I tried creating an index.d.ts file at the project's root, but that did not yield any results.

How can I define types for a native module in TypeScript?

MainApplication:

@Override
protected List<ReactPackage> getPackages() {
    @SuppressWarnings("UnnecessaryLocalVariable")
    List<ReactPackage> packages = new PackageList(this).getPackages();
    // Packages that cannot be autolinked yet can be added manually here, for example:
    // packages.add(new MyReactNativePackage());
    packages.add(new AndroidServicePackage());
    // packages.add(new MainReactPackage());
    return packages;
}

AndroidServicePackage:

@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
  return Arrays.<NativeModule>asList(new AndroidServiceModule(reactContext));
}

AndroidServiceModule:

@Override
public String getName() {
    return "AndroidService";
}

Method:

@ReactMethod
public void play(String streamingURL/*, ReadableMap options*/) {
  doSomething();
}

Answer №1

The import of NativeModules contains various native modules, allowing easy extraction of the AndroidService module as a property.

import NativeModules from 'react-native';
const { AndroidService } = NativeModules
export default { AndroidService }

Alternatively, you can export it simply like this:

import NativeModules from 'react-native';
exports.default = NativeModules.AndroidService;

If you have the native module named AndroidService added in a package for React Native, following these steps should give you the desired result.

Quoted from React Native's documentation on Native Modules

Answer №2

To resolve the issue, I made corrections to my import statements in the plugin's TypeScript file. The updated code is as follows:

import { NativeModules } from 'react-native';
const AndroidService = NativeModules.AndroidService;
export default AndroidService;

Answer №3

To properly access the AndroidService module in React Native, you need to surround your assignment with brackets for destructuring as shown below:

import { NativeModules } from 'react-native'; 
export const { AndroidService } = NativeModules

After that, you can use it in another file by importing it like this:

import { AndroidService } from 'path/to/exporting/file';

...

AndroidService.play("YOUR_URL"); 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The TypeScript error message reads: "You cannot assign type 'undefined' to type 'ReactElement'."

I'm encountering an error in my react project TypeScript error Argument of type 'ReactNode' is not compatible with parameter of type 'ReactElement<any, string | JSXElementConstructor<any>> | ReactElement<any, string | JSX ...

How can you pass additional information from an Activity to a Service in Kotlin?

I believe I've figured out how to add extras to my Intent, but I'm struggling to retrieve them Intent(this, MyService::class.java).also { intent -> bindService(intent, connection, Context.BIND_AUTO_CREATE) intent.putExtra("ip1&quo ...

Ways to troubleshoot opencv.js generating random values when applying cv.threshold

Whenever I choose an image and use cv.threshold, it outputs a strange number 6620912 The number seems to change at times https://i.sstatic.net/Tp9LP.png 6620912 Promise.catch (async) (anonymous) @ App.tsx:49 commitHookEffectListMount @ react-dom_client ...

Update not reflected in parent form when using ValueChanges in Angular's ControlValueAccessor

Here is the code snippet I am currently working with: https://stackblitz.com/edit/angular-control-value-accessor-form-submitted-val-egkreh?file=src/app/app.component.html I have set default values for the form fields, but when clicking the button, the pa ...

Incorrect TSX to JS compilation using Babel

I am attempting to use Babel to compile a directory of React TSX files into JavaScript files that can be read by browsers all in one go. Everything seems to be working fine, but the compiled JS output still contains the import statements from the TSX files ...

An error occurred while running React, Next.js, and Type Script: Unhandled Runtime Error - TypeError: Unable to access 'value' property of undefined

I have been working on a multi-page form and using the antd package to add some styling to it. On the main page of the form, I implemented the following code (making sure I imported everything required). export class CreateNewContract extends Component ...

What is the best way to enable the acceptance of a null value during the validation process of an optional

Currently, I am in the process of assembling a sandwich. Whenever all the necessary details are provided to Nest, everything operates smoothly and flawlessly. However, my predicament arises when attempting to assign null (empty string) to an enum, resultin ...

Ways to establish the relationship between two fields within an object

These are the definitions for two basic types: type AudioData = { rate: number; codec: string; duration: number; }; type VideoData = { width: number; height: number; codec: string; duration: number; }; Next, I need to create a MediaInfo typ ...

Guidelines for configuring an Android Socket.io client?

Once I've set up my SOCKET.IO server for a multi-room chat application, what is the best approach to developing the Android client using https://github.com/socketio/socket.io-client-java? I've done extensive research and have yet to find current ...

What is the method in TypeScript for defining a property in an interface based on the keys of another property that has an unknown structure?

I recently utilized a module that had the capability to perform a certain task function print(obj, key) { console.log(obj[key]) } print({'test': 'content'}, '/* vs code will show code recommendation when typing */') I am e ...

Will other functions in the file run if only a single function is imported?

The file bmiCalculator.ts contains the following code: import { isNotNumber } from './utils'; export default function calculateBmi(height: number, weight: number) { const bmi = weight / Math.pow(height / 100, 2); if (bmi < 18.5) { re ...

Display all values of an array in a single array using Angular

I have an array with values that are structured as shown in the image https://i.sstatic.net/SIo0N.png I am trying to consolidate them into a single array like { "1vwxnrjq", "dasdada", "adsdadsada"} console.log(items); this.ids = items.id; console.log(th ...

How can a custom event bus from a separate account be incorporated into an event rule located in a different account within the CDK framework?

In account A, I have set up an event rule. In account B, I have a custom event bus that needs to act as the target for the event rule in account A. I found a helpful guide on Stack Overflow, but it was specific to CloudFormation. I am providing another a ...

What is the best way to obtain the dimensions of an image in Angular 2 (or newer) before uploading it to the server, and can this be accomplished without utilizing jQuery?

After searching through multiple resources, I realized that most of the solutions are written in jQuery. However, I am specifically looking for a solution in Typescript. The HTML code snippet is as follows: <input #coverFilesInput class="file-input" t ...

What is the process for modifying a task on my to-do list with a long press?

I'm currently working on implementing a task update feature in my project. However, I've encountered an issue where the prompt only works in the browser environment. Is there a way to make this work in React Native or are there any alternative so ...

Test the HTML element using ngIf async call in Angular 2 with Jasmine unit testing

As I work on writing unit tests for an HTML div with a condition using *ngIf, I come across a specific scenario. <div *ngIf="clientSearchResults$ | async as searchResults" class = 'fgf' #datalist id="mydata" > <app-client-list id=" ...

I'm curious about the location of the definition for pageProps.session in Next-Auth

Upon reviewing the snippet import { SessionProvider } from "next-auth/react" export default function App({ Component, pageProps: { session, ...pageProps }, }) { return ( <SessionProvider session={session}> <Component {... ...

Typescript Error: The object doesn't recognize the property 'files' as part of the HTMLElement type

I am trying to implement an upload feature for my Apps using IONIC. Below is the HTML code snippet I have written: <input ion-button block type="file" id="uploadBR"> <input ion-button block type="file" id="uploadIC"> <button ion-button blo ...

Incorporate matTooltip dynamically into text for targeted keywords

I'm currently tackling a challenge in my personal Angular project that utilizes Angular Material. I'm struggling to find a solution for the following issue: For instance, I have a lengthy text passage like this: When you take the Dodge action, ...

A guide on effectively utilizing ref forwarding in compound component typing

I am currently working on customizing the tab components in Chakra-ui. As per their documentation, it needs to be enclosed within React.forwardRef because they utilize cloneElement to internally pass state. However, TypeScript is throwing an error: [tsserv ...