11
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Reactで指定の要素まで自動スクロールさせる

11
Last updated at Posted at 2017-09-05

はじめに

Reactで、ページ上部にスクロールや指定のidやclassまでスクロールさせたいことがあったので、Reactで使えるスクローラー作りました。

react-smooth-scroller

Github: https://github.com/gurimon/react-smooth-scroller

Installation

$ npm i -S react-smooth-scroller

or

$ yarn add react-smooth-scroller

Usage

// ES2015 imports
import rsScroller from 'react-smooth-scroller';

// ES5 require
const rsScroller = require('react-smooth-scroller');

API

rsScroller#scrollToTop(option)

rsScroller.scrollToTop();

// custom
rsScroller.scrollToTop({ easing: 'linear', duration: 1500, frame: 20, revise: 100 });

rsScroller#scrollToTarget(classname, option)

rsScroller.scrollToTarget('hoge');

// custom
rsScroller.scrollToTarget('hoge', { easing: 'linear', duration: 1500, frame: 20, revise: 100 });

rsScroller#scrollReset()

option

|Key|Type|Default|Description|
|---|---|---|---|---|
|easing|string|easeOutQuint|easing|
|duration|number|1000|all time|
|frame|number|13|one frame time|
|revise|number|0|revise pixel|

easing

  • linear
  • easeInQuad
  • easeOutQuad
  • easeInOutQuad
  • easeInCubic
  • easeOutCubic
  • easeInOutCubic
  • easeInQuart
  • easeOutQuart
  • easeInOutQuart
  • easeInQuint
  • easeOutQuint
  • easeInOutQuint
  • easeInSine
  • easeOutSine
  • easeInOutSine
  • easeInExpo
  • easeOutExpo
  • easeInOutExpo
  • easeInCirc
  • easeOutCirc
  • easeInOutCirc
  • easeInElastic
  • easeOutElastic
  • easeInBack
  • easeOutBack
  • easeInOutBack
  • easeInBounce
  • easeOutBounce
  • easeInOutBounce

Use with React

import React from 'react';
import rsScroller from 'react-smooth-scroller';

class Test extends Component {
  onScrollTop() {
    rsScroller.scrollToTop();
  }

  onScrollTarget(classname) {
    rsScroller.scrollToTarget(classname);
  }

  render() {
    return (
      <div className="test">
        <h1>react-smooth-scroller</h1>
        <div className="test__desc">
          <p>test</p>
          <a onClick={() => this.onScrollTarget('hoge')} className="btn">button-A</a>
        </div>
        <a onClick={() => this.onScrollTop()} className="btn hoge">button-B</a>
      </div>
    )
  }
});
11
8
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
11
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?