Continue event propagation with react-aria button component

335 Views Asked by At

The react-aria library disables event bubbling for buttons. I have a button nested inside a div which acts as a file uploader. When my button is clicked the file explorer doesn't pop up because event bubbling is disabled. How do I continue event propagation with my button so when it's clicked it gets treated as the parent div being clicked.

1

There are 1 best solutions below

0
On

Here is a 'solution' of sorts. Not convinced I'd recommend it but anyway it might help somebody.

Let's say your current implementation of the aria button looks like this:

const AriaButton = (props: AriaButtonProps) => {
  const {
    children,
    id,
    title,
    ...rest
  } = props;

  const ref = useRef(null);

  const { buttonProps } = useButton(rest, ref);

  return (
    <button
      title={title}
      id={id}
      {...buttonProps}
      ref={ref}
    >
      {children}
    </button>
  );
};

export default AriaButton;

By decorating the onPress function prior to passing it into the useButton hook you can go ahead and fire it as normal but also immediately afterwards simulate a click on the button's parent element

const AriaButton = (props: AriaButtonProps) => {
  const onPress = props.onPress;

  props = {
    ...props,
    onPress: (e: AriaPressEvent) => {
      onPress?.(e);
      e.target.parentElement?.click();
    },
  };

  const {
    children,
    id,
    title,
    ...rest
  } = props;

  const ref = useRef(null);

  const { buttonProps } = useButton(rest, ref);

  return (
    <button
      title={title}
      id={id}
      {...buttonProps}
      ref={ref}
    >
      {children}
    </button>
  );
};

export default AriaButton;