Skip to content

Commit 62f013c

Browse files
committed
fix: fix onClick prop collisions by adding an event directly
1 parent e3074d2 commit 62f013c

File tree

2 files changed

+11
-12
lines changed

2 files changed

+11
-12
lines changed

README.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,6 @@ const Button = () => {
104104

105105
```ts
106106
{
107-
readonly onClick: (event: React.MouseEvent<T, MouseEvent>) => void;
108107
readonly role: "button";
109108
readonly tabIndex: 0;
110109
}

src/index.tsx

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,26 +3,26 @@ import useKey from '@accessible/use-key'
33
import useEvent from '@react-hook/event'
44
import useMergedRef from '@react-hook/merged-ref'
55

6-
export function useA11yButton<
7-
T extends HTMLElement,
8-
E extends React.MouseEvent<T, MouseEvent>
9-
>(target: React.RefObject<T> | T | null, onClick: (event: E) => any) {
6+
export function useA11yButton<T extends HTMLElement>(
7+
target: React.RefObject<T> | T | null,
8+
onClick: (event: MouseEvent) => any
9+
) {
1010
const clickedMouse = React.useRef(false)
1111
const setClickedMouse = () => (clickedMouse.current = true)
1212
useEvent(target, 'touchstart', setClickedMouse)
1313
useEvent(target, 'mousedown', setClickedMouse)
14+
useEvent(target, 'click', (event) => {
15+
// Only fire onClick if the keyboard was not used to initiate the click
16+
clickedMouse.current && onClick(event)
17+
clickedMouse.current = false
18+
})
1419
// @ts-expect-error
1520
useKey(target, {
1621
Enter: onClick,
1722
' ': onClick,
1823
})
1924

2025
return {
21-
onClick: (event: E) => {
22-
// Only fire onClick if the keyboard was not used to initiate the click
23-
clickedMouse.current && onClick(event)
24-
clickedMouse.current = false
25-
},
2626
role: 'button',
2727
tabIndex: 0,
2828
} as const
@@ -31,10 +31,10 @@ export function useA11yButton<
3131
export const Button = ({children}: ButtonProps) => {
3232
const ref = React.useRef(null)
3333
const {props} = children
34-
const {onClick, role, tabIndex} = useA11yButton(ref, props.onClick)
34+
const {role, tabIndex} = useA11yButton(ref, props.onClick)
3535

3636
return React.cloneElement(children, {
37-
onClick,
37+
onClick: undefined,
3838
role: props.hasOwnProperty('role') ? props.role : role,
3939
tabIndex: props.hasOwnProperty('tabIndex') ? props.tabIndex : tabIndex,
4040
// @ts-expect-error

0 commit comments

Comments
 (0)