Created
May 23, 2024 06:50
-
-
Save BrianHung/84e86882201adeb6a6c6a7bf70fcbd36 to your computer and use it in GitHub Desktop.
Horizontal Resizable React Component
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'; | |
const ResizableDiv = function ResizableDiv(props: { onChange: (dx: number) => void }) { | |
const { onChange = () => null, ...otherProps } = props; | |
const resizeRef = React.useRef<HTMLElement | null>(null); | |
const [resizing, setResizing] = React.useState(false); | |
const handlePointerDown = React.useCallback( | |
(event: React.PointerEvent) => { | |
setResizing(true); | |
event.preventDefault(); | |
function handlePointerMove(event: PointerEvent) { | |
event.preventDefault(); | |
window.requestAnimationFrame(() => { | |
const rect = resizeRef.current!.getBoundingClientRect(); | |
onChange?.(event.x - rect.x); | |
}); | |
} | |
function handlePointerUp() { | |
setResizing(false); | |
document.removeEventListener('pointermove', handlePointerMove); | |
document.removeEventListener('pointerup', handlePointerUp); | |
} | |
document.addEventListener('pointermove', handlePointerMove); | |
document.addEventListener('pointerup', handlePointerUp); | |
}, | |
[onChange] | |
); | |
return ( | |
<div | |
style={{ | |
position: 'absolute', | |
left: 0, | |
width: 0, | |
flexGrow: 0, | |
zIndex: 1, | |
top: 0, | |
bottom: 0, | |
pointerEvents: 'auto', | |
}} | |
> | |
<div | |
style={{ cursor: 'col-resize', height: '100%', width: '4px', marginLeft: '-2px' }} | |
onPointerDown={handlePointerDown} | |
aria-grabbed={String(resizing)} | |
ref={resizeRef} | |
{...otherProps} | |
/> | |
</div> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment