0
0

React Projectでスムーズなスクロールを実装する際の備忘録

Posted at

執筆の動機

Reactでポートフォリオを作成していた際に、スムーズスクロールを実装しようと考え様々なサイトを当たったが、どのサイトもReactベースではなく、何も考えずコピペ実装したかった私のニーズに合うページが見つからなかった。

前提

以降はこのディレクトリ構成を前提として解説する。

src
├── App.js
├── App.test.js
├── SmoothScroll.js
├── index.css
├── index.js
├── reportWebVitals.js
├── setupTests.js
└── styles
    ├── App.css
    └── Navbar.css

locomotive-scrollとは

Perry Wang氏のポートフォリオを眺めていた際に、スクロールの動きの美しさに惚れたのがきっかけ(一度は見た方がいい美しいポートフォリオです。他にも様々参考になる点がありました。)でlocomotive-scrollに出会いました。
簡単にスムーズスクロールが実装できるので嬉しいというメリットがあります。

実装

npm install

プロジェクトのディレクトリに移動したら

npm i locomotive-scroll

を実行し、インストール。

React Componentの作成

/src/components/SmoothScroll.js
import React, { useEffect, useRef } from 'react';
import LocomotiveScroll from 'locomotive-scroll';

const SmoothScroll = ({ children }) => {
  const scrollRef = useRef(null);

  useEffect(() => {
    const scroll = new LocomotiveScroll({
      el: scrollRef.current,
      smooth: true,
    });

    return () => {
      if (scroll) scroll.destroy();
    };
  }, []);

  return <div data-scroll-container ref={scrollRef}>{children}</div>;
};

export default SmoothScroll;

Componentの配置

以下のように、適用されて欲しい範囲をSmoothScrollで囲ってあげればOK。

/src/App.jsx
import React from 'react';
import SmoothScroll from './components/SmoothScroll';
import './App.css';

const App = () => {
  return (
    <SmoothScroll>
      <main>
        {/* ここにプロジェクトの大部分をブチ込む */}
      </main>
    </SmoothScroll>
  );
};

export default App;

まとめ

以上ReactでLocomotive scrollを実装する方法でした。思ったより簡単にできるのでみなさんもぜひ実装してみてください!ヌルヌルスクロールできてQOL上がります!

0
0
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
0
0