LoginSignup
16
12

More than 3 years have passed since last update.

【React】overflow: scrollコンテンツにスムーススクロールを実装する

Last updated at Posted at 2017-12-09

初投稿です。

最近業務でReactを使い始めました。
難しいですが楽しいですよね。React。
さて、今回はoverflow: scroll コンテンツ内でスムーススクロールさせる方法をご紹介します。
方法はとても簡単なのですが、今回使用したreact-scrollというライブラリの公式サンプルが詰め込むだけ詰め込んだ形で私的には読みづかったのでピンポイントで実装方法をご紹介します。

実装方法:hammer_pick:

方法はざっくり2パターンあると思っていて、

  1. CSSプロパティ scroll-behavior: smooth を使う
  2. JSで書く(今回はreact-scrollというライブラリを使う)

1.に関してはCSS1つ追加するだけなのでシンプルです。ただし、Chrome,FireFox以外のブラウザではPolyfillしないと動作しないので注意して下さい。can i use scroll-behavior?

今回は2の方法を詳しく説明します。

react-scrollを使う:hammer_pick:

react-scrollはReact Componentにスクロール機能を与えるライブラリです。ライセンスはMITです。早速ですがoverflow:scroll内の任意地点までスムーススクロールさせる方法を見ていきましょう。

import React,{ Component } from 'react'
import { Link } from 'react-scroll'

class OverFlowContent extends Component {
  render() {
    return (
      <div>
        <Link to="link1" smooth={true} duration={250} containerId="overFlowScrollArea">リンク1へ</Link>
        <Link to="link2" smooth={true} duration={250} containerId="overFlowScrollArea">リンク2へ</Link>
        <Link to="link3" smooth={true} duration={250} containerId="overFlowScrollArea">リンク3へ</Link>
        <div id="overFlowScrollArea">
          <div name="link1">リンク1</div>
          <div name="link2">リンク2</div>
          <div name="link3">リンク3</div>
        </div>
      </div>
    }
  )
}
import { Link } from 'react-scroll'

スムーススクロールを実装したい場合、読み込むのはたったこれだけです。ポイントは2つで、

  • <Link />Componentのto="link1と"name="link1"がそれぞれリンクになっている
  • <Link />ComponentのcontainerId="overFlowScrollArea"がスクロールイベントをリッスンして、実際にスクロールを実行するコンテナとなる

公式は<Element />Componentをimportしていたり、不要なclassやIDの指定があり少々混乱するかもしれません。基本的には<Link />Componentにto="hoge"とそれに対応するname="hoge"があればリンクとして機能します。そして今回はスムーススクロールなので、smooth={true}にしておきduration={}は好きな速さに設定してください。

そして大事なのはcontainerIdを確実に指定することです。これがないと、overflow: scrollのコンテンツ内でスクロールしません。

まとめ

はやくscroll-behavior: smoothが標準実装された世界線に行きたい。

16
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
12