0
0

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 3 years have passed since last update.

React.jsで同ページ内でScrollアニメーションの追加方法

Posted at

(1)yarn add react-scroll

(2)

index.tsx
import { animateScroll as scroll } from 'react-scroll'

const Home: React.FC = () => {
  const scrollToTop = () => {
    scroll.scrollToTop()
  }
  return (
	<div className={styles.container}>
	  <BackButton className={styles.backButton} onBackClick={scrollToTop} />
	</div>
     ...

(3)ページ内の特定の場所にスクロールする
SectionQuestionというコンポネントにidというPropsが渡されています。
pagesの呼び出し先で、idを設定します。

scrollToQというreact-scrollの関数を用意し、以下のようにオプションを追加します。
duration:スクロールにかかる秒数
delay: 遅延
smooth: アニメーションスクロール
offset: idのコンポーネントの上端からずらす

スクロールのトリガーにしたいボタンの、onClickにscrollToQを渡すと、SectionQuestionにスクロールする。

index.tsx
import SectionQuestion from '../../components/domains/SectionQuestion'
import { animateScroll as scroll, scroller } from 'react-scroll'
import Footer from '../../components/domains/Footer'

export const Index = () => {
  const scrollToQ = () => {
    scroller.scrollTo('question', {
      duration: 1000,
      delay: 0,
      smooth: true,
      offset: -50,
    })
  }
  return (
    <div>
      <SectionQuestion id="question" />
      <Footer
        onAboutClick={scrollToQ}
      />
    </div>
  )
}

オプションの詳細はgithubに載っています。
https://github.com/fisshy/react-scroll

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?