Open
Description
Not sure if you would find this useful, and it would not be a breaking change for previous users... but I wrote the following component to simplify the boiler plate code needed to handle the onPress
event for the context menu! Cheers:
import React from 'react';
import { NativeSyntheticEvent } from 'react-native';
import RNContextMenu, {
ContextMenuOnPressNativeEvent,
ContextMenuAction as RNContextMenuAction,
ContextMenuProps as RNContextMenuProps,
} from 'react-native-context-menu-view';
export type ContextMenuAction = Omit<RNContextMenuAction, 'actions'> & {
onPress?: (e: NativeSyntheticEvent<ContextMenuOnPressNativeEvent>) => void;
actions?: ContextMenuAction[];
};
export type ContextMenuProps = Omit<RNContextMenuProps, 'actions'> & {
actions?: ContextMenuAction[];
};
export const ContextMenu = React.forwardRef<RNContextMenu>(function ContextMenu({
actions,
onPress,
previewBackgroundColor = 'transparent',
...props
}: ContextMenuProps, ref) {
const menuRef = React.useRef<RNContextMenu>(null);
React.useImperativeHandle(ref, () => menuRef.current as RNContextMenu);
const menuHandler = React.useCallback((e: NativeSyntheticEvent<ContextMenuOnPressNativeEvent>) => {
console.log(e.nativeEvent.index, e.nativeEvent.indexPath);
if (onPress) {
onPress(e);
} else {
const reduce = (acc: ContextMenuAction | ContextMenuAction[], index: number) => Array.isArray(acc) && Array.isArray(acc?.[index]?.actions) ? acc?.[index]?.actions : Array.isArray(acc) ? acc?.[index] : acc;
const action = e.nativeEvent.indexPath.reduce(reduce, actions ?? []) as ContextMenuAction;
action?.onPress?.(e);
}
e.preventDefault();
e.stopPropagation();
}, [onPress, actions]);
return (
<RNContextMenu
ref={ ref }
actions={ actions }
onPress={ menuHandler }
previewBackgroundColor={ previewBackgroundColor }
{ ...props } />
);
}) as React.ForwardRefExoticComponent<ContextMenuProps & React.RefAttributes<RNContextMenu>>;
Metadata
Metadata
Assignees
Labels
No labels