react-indiana-drag-scroll – npm
React Indiana Drag Scroll はマウスによるドラッグでスクロールを行う機能を React 内で HTML やコンポーネントに持たせるためのライブラリです。使い方は React Indiana Drag Scroll から渡されるコンポーネントでスクロール範囲を括るのみです。具体的には次です。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | import React from "react" ; import "./styles.css" ; import ScrollContainer from "react-indiana-drag-scroll" ; /** min から max までの数字の入った配列を生成する関数 */ const range = (min, max, step = 1) => { return Array.from( { length: (max - min + step) / step }, (v, k) => min + k * step ); }; export default function App() { return ( <div className= "App" > <h1>React Indiana Drag Scrollデモ</h1> <p>↓の箱の上でドラッグをするとスクロールが起きます</p> <div style={{ position: "relative" , overflow: "hidden" , border: "solid" }} > { /** ScrollContainer でドラッグ範囲を括ります */ } { /** ignoreElements にドラッグしない部分を指すセレクタを入れると、その上からスクロールできません */ } <ScrollContainer ignoreElements={ "#not-work-drag" }> <div id= "not-work-drag" style={{ height: "100%" , background: "rgba(0, 208, 255, 0.8)" , position: "absolute" , display: "flex" , flexDirection: "column" , justifyContent: "space-between" , left: "12%" }} > <div>この上では</div> <div>ドラッグしてもスクロールしません</div> </div> <div style={{ display: "flex" }}> {range(0, 100).map((i) => ( <div style={{ margin: "1em .25em" }}>{i}</div> ))} </div> </ScrollContainer> </div> </div> ); } |
便利ながら分かりにくい props に ignoreElements があります。これに渡すと渡されたセレクタに該当する HTML 要素の上からはドラッグによるスクロールが働かなくなります。
基本的な設定は props から渡せますが内部の HTML 要素にアクセスすることも可能です。外から命令的にスクロール状態を制御するには次のコードの様に HTML 要素から素のJavaScript 的に色々するのがよいです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | export default function App() { const scrollRef = React.createRef(); // scrollRef が変化したら適当な場所に向かってスクロールを実行 React.useEffect(() => { if (!scrollRef.current) { return ; } const scrollRefElement = scrollRef.current?.getElement(); scrollRefElement.scrollTo( Math.random() * scrollRefElement.getBoundingClientRect().width, 0 ); }, [scrollRef]); return ( <ScrollContainer ref={scrollRef}> { /* スクロール内容 */ } </ScrollContainer> ); } |