LoginSignup
4
0

More than 1 year has passed since last update.

ReactでscrollRevealを使用する

Last updated at Posted at 2022-02-18

refとカスタムhookの概念の解像度があがったのでmemoします。

ScrollRevealとは

JQueryを使用せずアニメーションを付けられるライブラリ。
https://scrollrevealjs.org/

1.インストール

HTMLで

<script src="https://unpkg.com/scrollreveal"></script>

を読み込む。

もしくはnpmでインストール。

npm install scrollreveal --save

私は後者で進めました。

2.メソッド ScrollReveal().reveal('');

アニメーションをつけるには
ScrollReveal().reveal('');
のメソッドを使って、HTMLのclassに指定する。
''の中には指定するclass名が入ります。

Vanilla jsで書いてみた↓

Edit sy2ep3

3.Reactのコンポーネント化

ここが難しくて苦戦しました。refを理解する良い機会になりました。

ScrollReveal.js
import React, { Component } from "react";
import ScrollReveal from "scrollreveal";
import { useRef, useEffect } from "react";

const Scroll = ({ children }) => {

  const sectionRef = useRef();
  useEffect(() => {
    if (sectionRef.current) {
      ScrollReveal().reveal(sectionRef.current, {
        reset: true,
        delay: 700,
        opacity: 0,
        distance: "40px",
      });
    }
  },[]);

  return (<section ref={sectionRef}>{children}</section>)
}

export{ Scroll }

useRefで該当のコンポーネントまでスクロールした時にDOMを参照します。
useEffectを使うことで、対象のDOMが参照されるたびにScrollReveal().revealが実行されます。

Main.js
import {Scroll} from './ScrollReveal.jsx'

export const Main = () => {
return(
            <Scroll>
            <h1>
              Web designer
              <br />
              Front-end developper
            </h1>
            </Scroll>

上記のようにでアニメーションを付けたい箇所を囲って完成です。

参考にした記事
https://qiita.com/uwattotaitai/items/5957eda0c63634fbaa56
https://qiita.com/tonio0720/items/c265b9b65db3bb76f2d3
https://zenn.dev/butter67/articles/2020-09-23first-article

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