1
1

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.

Next.jsでボタンを押したら特定セクションまでスクロールさせたい

Posted at

環境

  • M2 Mac 12.5.1
  • Node.js 16.17.1
  • Next.js 12.3.1
  • tailwind 3.1.8
  • GoogleChrome 105.0.5195.125

やりたいこと

ボタンを押したら特定セクションまでスクロールさせたい
見てもらった方が早いので、こんな感じ

Qiitaの目次って言った方が伝わるかな?

やりかた

1.スクロール先となる箇所にidを振っておく

一意に特定できるならidじゃなくても良いと思う

index.tsx
<h1 id="section-profile" className="text-3xl pt-40 md:pt-20">
  Profile
</h1>
<Profile />

2.Linkコンポーネントのhrefidセレクタを指定する

index.tsx
import Link from 'next/link'

<Link href="#section-profile">
  <a className="px-3 hover:underline decoration-c2 hover:decoration-4">Profile</a>
</Link>

注意点

ナビゲーションバーなどをposition: fixed;で指定していると、スクロールされた後に要素が隠れてしまうので、必要に応じてpaddingを設定してやる
上記1.のサンプルコードのpt-40 md:pt-20はそのために指定している

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?