Skip to main content

View commands

Commands declaration

To add commands to native component, JS spec needs to commands object made with codegenNativeCommands method:

src/MyAwesomeViewNativeComponent.ts
import * as React from 'react';
import type { HostComponent, ViewProps } from 'react-native';
import type { Double } from 'react-native/Libraries/Types/CodegenTypes';
import codegenNativeCommands from 'react-native/Libraries/Utilities/codegenNativeCommands';
import codegenNativeComponent from 'react-native/Libraries/Utilities/codegenNativeComponent';

export interface MyAwesomeViewProps extends ViewProps {}

export interface MyAwesomeViewNativeCommands {
doAwesomeJob: (viewRef: React.ElementRef<<HostComponent<MyAwesomeViewProps>>>, arg: Double) => void
}

export const MyAwesomeViewCommands = codegenNativeCommands<MyAwesomeViewNativeCommands>({
supportedCommands: [ 'doAwesomeJob' ],
});

export default codegenNativeComponent<MyAwesomeViewProps>('MyAwesomeView') as HostComponent<MyAwesomeViewProps>;

Commands implementation in native code

ios/MyAwesomeViewComponentView.mm
#import <react/renderer/components/MyAwesomeView/RCTComponentViewHelpers.h>

// ...

@interface MyAwesomeViewComponentView () <RCTMyAwesomeViewViewProtocol>
@end

// ...

- (void)handleCommand:(const NSString *)commandName args:(const NSArray *)args
{
RCTMyAwesomeViewHandleCommand(self, commandName, args);
}

- (void)doAwesomeJob:(double)arg
{
// ...
}

To implement commands for iOS native component, it has to extend code-generated protocol and implement - handleCommand:args: method, as well as method declared in JS spec (via code-generated protocol).