Last active
June 7, 2020 06:50
-
-
Save francoisgeorgy/0dd6b33be036e5b1d37e65f0f6d39fa4 to your computer and use it in GitHub Desktop.
#React resizable panel #typescript
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, {FunctionComponent, useEffect, useRef, useState} from "react"; | |
| import "./ResizablePanel.css"; | |
| // ResizablePanel.css: | |
| /* | |
| .resizable-panel { | |
| display: flex; | |
| justify-content: space-between; | |
| } | |
| .resize-wrapper { | |
| flex-grow: 2; | |
| } | |
| .resizable-panel-options { | |
| width: 20px; | |
| text-align: right; | |
| } | |
| .slider-wrapper { | |
| display: inline-block; | |
| width: 20px; | |
| height: 120px; | |
| padding: 0; | |
| text-align: right; | |
| } | |
| .slider-wrapper input { | |
| width: 120px; | |
| height: 20px; | |
| margin: 0; | |
| transform-origin: 60px 60px; | |
| transform: rotate(-90deg); | |
| } | |
| */ | |
| interface PanelProps { | |
| children: React.ReactNode | |
| } | |
| export const ResizablePanel: FunctionComponent<PanelProps> = ({children}: PanelProps) => { | |
| const wrapper = useRef(null); | |
| useEffect(() => { | |
| const handleResize = () => { | |
| // @ts-ignore | |
| // console.log(`handleResize: win=${window.innerWidth}, wrapper=${wrapper.current.offsetWidth}`); | |
| // @ts-ignore | |
| if ((window.innerWidth - 60) < wrapper.current.offsetWidth) { | |
| // console.log("handleResize force resize"); | |
| setSize(100); | |
| } | |
| }; | |
| window.addEventListener("resize", handleResize) | |
| return () => { | |
| window.removeEventListener("resize", handleResize) | |
| }; | |
| }, []); | |
| const [size, setSize] = useState(100); | |
| function resize(w: number) { | |
| setSize(w); | |
| } | |
| let ww; | |
| if (size === 100 || !wrapper === null || !wrapper.current) { | |
| ww = '100%'; | |
| } else { | |
| // @ts-ignore | |
| ww = `${wrapper.current.offsetWidth / 100 * size}px`; | |
| } | |
| return ( | |
| <div className={"panel resizable-panel"}> | |
| <div className="resize-wrapper" ref={wrapper}> | |
| <div style={{width:ww}}> | |
| {children} | |
| </div> | |
| </div> | |
| <div className={"resizable-panel-options"} style={{width:`30px`}}> | |
| <div className="slider-wrapper"> | |
| <input type="range" min="66" max="100" value={size} step="1" onChange={(e) => resize(parseInt(e.target.value, 10))} /> | |
| </div> | |
| </div> | |
| </div> | |
| ); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment