Last active
January 23, 2023 08:45
-
-
Save tilap/dc3d6730af28f2227a443b76efe09414 to your computer and use it in GitHub Desktop.
React native hook to automatically add hit slop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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