Skip to content

Instantly share code, notes, and snippets.

@ManiruzzamanAkash
Created February 4, 2025 08:26
Show Gist options
  • Save ManiruzzamanAkash/61900eb97e89b471ad746538f2847395 to your computer and use it in GitHub Desktop.
Save ManiruzzamanAkash/61900eb97e89b471ad746538f2847395 to your computer and use it in GitHub Desktop.
Resize Editor or Component - React
import { useState, useCallback } from 'react';
const ResizableHandler = ({ children }) => {
const [width, setWidth] = useState('100%');
const [isResizing, setIsResizing] = useState(false);
const [startX, setStartX] = useState(0);
const startResizing = useCallback((event) => {
setIsResizing(true);
setStartX(event.clientX);
}, []);
const stopResizing = useCallback(() => {
setIsResizing(false);
}, []);
const resize = useCallback(
(event) => {
if (isResizing) {
const delta = event.clientX - startX;
setWidth((prevWidth) => {
const newWidth = parseInt(prevWidth) + delta;
return newWidth > 200 ? `${newWidth}px` : '200px';
});
setStartX(event.clientX);
}
},
[isResizing, startX]
);
return (
<div
className="sc-resizable-handler"
style={{
width: width,
display: 'flex',
flexDirection: 'row',
overflow: 'auto',
position: 'relative',
margin: '0 auto',
}}
onMouseMove={resize}
onMouseUp={stopResizing}
>
{/* Add left side bar */}
<div
style={{
width: '10px',
cursor: 'ew-resize',
backgroundColor: '#ccc',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
position: 'absolute',
left: 0,
top: 0,
bottom: 0,
zIndex: 1,
}}
onMouseDown={startResizing}
>
<div
style={{
width: '2px',
height: '100%',
backgroundColor: '#888',
}}
/>
</div>
<div
style={{
flexGrow: 1,
}}
>
{children}
</div>
{/* Add right side bar */}
<div
style={{
width: '10px',
cursor: 'ew-resize',
backgroundColor: '#ccc',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
position: 'absolute',
right: 0,
top: 0,
bottom: 0,
zIndex: 1,
}}
onMouseDown={startResizing}
>
<div
style={{
width: '2px',
height: '100%',
backgroundColor: '#888',
}}
/>
</div>
</div>
);
};
export default ResizableHandler;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment