App Routerでアクセシブルなアコーディオンとスクロール表示を実装する

「NEXT BASE」(旧 NEXT TECH)の FAQ ページのアコーディオンと、全ページ共通のスクロール表示の実装を紹介します。どちらもライブラリを使わず、キーボード操作と表示崩れの対策まで入れています。Next.js 16・React 19 に上げたときに、スクロール表示の条件と、ヘッダーの時計の書き方も見直しました。
リポジトリ:Nextjs-TypeScript-MicroCMS-Site2 / デモ:https://next-tech-trigger.vercel.app/
FAQ アコーディオン
開いている質問の番号を配列で持つので、複数の質問を同時に開けます。dt をボタンとして扱うため、role・tabIndex・aria-expanded・aria-controls を付けています。
<dt
onClick={() => handleToggleQuestion(index)}
onKeyDown={(e) => handleKeyDown(e, index)}
role="button"
tabIndex={0}
aria-expanded={isOpen}
aria-controls={`faq-answer-${index}`}
>
{faq.question}
</dt>
<dd id={`faq-answer-${index}`} style={{ display: isOpen ? 'block' : 'none' }}>
{faq.answer}
</dd>
div や dt をボタンにするときは、Enter と Space でも操作できるようにする必要があります。Space はそのままだとページがスクロールしてしまうので、preventDefault() を呼びます。
const handleKeyDown = (event: KeyboardEvent<HTMLElement>, index: number) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault()
handleToggleQuestion(index)
}
}
スクロール表示:RevealObserver
data-reveal を付けた要素が画面に入ったら data-shown を付け、CSS で表示します。レイアウトに 1 つだけ置く Client Component で、何も描画しません(return null)。
'use client'
export const RevealObserver = () => {
const pathname = usePathname()
useEffect(() => {
const selector = '[data-reveal]:not([data-shown])'
// IntersectionObserver がない環境では、最初から全部表示する
if (typeof IntersectionObserver === 'undefined') {
document.querySelectorAll(selector).forEach((el) => el.setAttribute('data-shown', ''))
return
}
const io = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
entry.target.setAttribute('data-shown', '')
io.unobserve(entry.target)
}
})
}, { threshold: 0, rootMargin: '0px 0px -10% 0px' })
const scan = () => document.querySelectorAll(selector).forEach((el) => io.observe(el))
scan()
const mo = new MutationObserver(scan)
mo.observe(document.body, { childList: true, subtree: true })
return () => { io.disconnect(); mo.disconnect() }
}, [pathname])
return null
}
工夫した点は 3 つです。
usePathname()を依存配列に入れ、ページ遷移のたびに監視し直すMutationObserverで、後から追加された要素(ストリーミングで届いた部分など)も監視対象にするthresholdを0にして、画面の下 10% より上に入ったところで表示する
3 つ目は、作り直したときに見つけた不具合の対策です。以前は threshold: 0.12(要素の 12% が見えたら表示)にしていましたが、長い記事の本文のように画面より大きな要素は、12% が一度に見えることがなく、いつまでも表示されませんでした。割合ではなく「画面に入ったかどうか」で判定するようにして解決しました。
おまけ:時計のハイドレーションエラー対策
ヘッダーの「TOKYO 08:02」はサーバーとブラウザで時刻がずれるため、そのまま描画するとハイドレーションエラーになります。以前は初期値を '--:--' にして useEffect の中で時刻を入れていましたが、React の useSyncExternalStore を使う形に書き換えました。
'use client'
import { useSyncExternalStore } from 'react'
const format = () =>
new Date().toLocaleTimeString('en-GB', { timeZone: 'Asia/Tokyo', hour: '2-digit', minute: '2-digit' })
// 10 秒ごとに時刻を読み直す
const subscribe = (onChange: () => void) => {
const id = setInterval(onChange, 10000)
return () => clearInterval(id)
}
export const Clock = () => {
// 3 つ目の引数がサーバーでの値。ブラウザに切り替わってから本当の時刻になる
const time = useSyncExternalStore(subscribe, format, () => '--:--')
return <span>TOKYO <time>{time}</time></span>
}
useSyncExternalStore は、React の外にある値(ここでは現在時刻)を読むためのフックです。3 つ目の引数にサーバーで使う値を渡せるので、サーバーとブラウザの食い違いが起きません。useState と useEffect を組み合わせるより短く書け、タイマーの後片付けも subscribe の戻り値にまとまります。
まとめ
- ボタン以外をボタンにするなら、
role・tabIndex・aria属性・キーボード操作をそろえる - スクロール表示は
IntersectionObserver+MutationObserverで、遷移後や遅れて届く要素にも対応する - 画面より大きな要素があるなら、
thresholdは割合ではなく0にする - 時刻など環境で変わる値は、
useSyncExternalStoreでサーバーの値とブラウザの値を分ける