Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion - Wrapper Component to automatically handle On Press #140

Open
NoodleOfDeath opened this issue Nov 19, 2024 · 0 comments
Open

Comments

@NoodleOfDeath
Copy link

NoodleOfDeath commented Nov 19, 2024

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>>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant