cta.ts 857 B

123456789101112131415161718192021222324252627282930313233343536
  1. import React, { ReactEventHandler, useMemo } from 'react';
  2. export const isEnter = (event: KeyboardEvent | React.KeyboardEvent): boolean =>
  3. event.key === 'Enter';
  4. type Options = {
  5. stopPropagation?: boolean;
  6. };
  7. export function useCTA<E extends HTMLElement = HTMLElement>(
  8. onActivate: () => void,
  9. options?: Options,
  10. ): {
  11. onClick: ReactEventHandler<E>;
  12. onKeyDown: ReactEventHandler<E>;
  13. } {
  14. const stopPropagation = !!options?.stopPropagation;
  15. const events = useMemo(
  16. () => ({
  17. onKeyDown: (event: React.KeyboardEvent<E>): void => {
  18. if (isEnter(event)) {
  19. onActivate();
  20. }
  21. },
  22. onClick: (event: React.MouseEvent<E>): void => {
  23. if (stopPropagation) {
  24. event.stopPropagation();
  25. }
  26. onActivate();
  27. },
  28. }),
  29. [onActivate, stopPropagation],
  30. );
  31. return events;
  32. }