@intility/bifrost-react
Version:
React library for Intility's design system, Bifrost.
33 lines (32 loc) • 1.03 kB
JavaScript
// When onClick is provided to a component
// component should have tabIndex and keyboard bindings
// this function return value can be spread on a native element
// makes the element simulate what a button element natively does
const accessibleOnClick = (props, onClick)=>{
if (typeof onClick === "function") {
return {
onClick,
role: "button",
tabIndex: 0,
onKeyDown: (e)=>{
if (e.key === "Enter") {
e.preventDefault();
if (!e.repeat) {
onClick(e);
}
} else if (e.key === " ") {
e.preventDefault();
}
props.onKeyDown?.(e);
},
onKeyUp: (e)=>{
if (e.key === " ") {
e.preventDefault();
onClick(e);
}
props.onKeyUp?.(e);
}
};
}
};
export default accessibleOnClick;