Skip to content

Instantly share code, notes, and snippets.

@tilap
Last active January 23, 2023 08:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tilap/dc3d6730af28f2227a443b76efe09414 to your computer and use it in GitHub Desktop.
Save tilap/dc3d6730af28f2227a443b76efe09414 to your computer and use it in GitHub Desktop.
React native hook to automatically add hit slop
import React from 'react';
import type { LayoutChangeEvent, Insets } from 'react-native';
const defaultGetHitSlopForSize = ({ width, height }: Framesize): Insets => {
const x = width > 44 ? 0 : 10;
const y = height > 44 ? 0 : 10;
return { top: y, bottom: y, left: x, right: x };
};
type Framesize = { width: number; height: number };
type GetHitSlopForSize = (size: Framesize) => Insets;
function useAutoHitSlop(callback?: GetHitSlopForSize) {
const [frameSize, setFrameSize] = React.useState<Framesize>({ width: 0, height: 0 });
const onLayout = React.useCallback(
(event: LayoutChangeEvent) => {
const {
nativeEvent: { layout },
} = event;
if (layout.width !== frameSize.width && layout.height !== frameSize.height) {
setFrameSize({ width: layout.width, height: layout.height });
}
},
[frameSize]
);
return { hitSlop: (callback || defaultGetHitSlopForSize)(frameSize), onLayout };
}
export default useAutoHitSlop;
import useAutoHitSlop from './autoHitSlop';
import React from 'react';
import { TouchableOpacity, TouchableOpacityProps } from 'react-native';
type Props = Partial<Pick<TouchableOpacityProps, 'hitSlop' | 'onLayout'>> & {
children?: string | React.ReactNode;
};
const TrucBidule: React.FC<Props> = ({ children, ...rest }) => {
const { hitSlop, onLayout } = useAutoHitSlop();
return (
<TouchableOpacity hitSlop={hitSlop} onLayout={onLayout} {...rest} >
{children}
</TouchableOpacity>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment