Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
chore: add generic ref support for useClickable
  • Loading branch information
Parkreiner committed Sep 22, 2023
commit 0d8832416beffd3dfd99aeb0fc607c33beed51a3
35 changes: 30 additions & 5 deletions site/src/hooks/useClickable.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,45 @@
import { KeyboardEvent } from "react";
import {
type MouseEventHandler,
type KeyboardEvent,
type RefObject,
useRef,
} from "react";

export interface UseClickableResult {
// Literally any object (ideally an HTMLElement) that has a .click method
type ClickableElement = {
click: () => void;
};

export interface UseClickableResult<
T extends ClickableElement = ClickableElement,
> {
ref: RefObject<T>;
tabIndex: 0;
role: "button";
onClick: () => void;
onClick: MouseEventHandler<T>;
onKeyDown: (event: KeyboardEvent) => void;
}

export const useClickable = (onClick: () => void): UseClickableResult => {
export const useClickable = <
// T doesn't have a default type to make it more obvious that the hook expects
// a type argument in order to work at all
T extends ClickableElement,
>(
onClick: MouseEventHandler<T>,
): UseClickableResult<T> => {
const ref = useRef<T>(null);

return {
ref,
tabIndex: 0,
role: "button",
onClick,
onKeyDown: (event: KeyboardEvent) => {
if (event.key === "Enter") {
onClick();
// Can't call onClick directly because onClick needs to work with an
// event, and mouse events + keyboard events aren't compatible; wouldn't
// have a value to pass in. Have to use a ref to simulate a click
ref.current?.click();
}
},
};
Expand Down