Next.jsでアクセシブルなインラインSVGを使う


こんにちは、みみです。

Next.js + TypeScript でインラインSVGを使いたい時にどうするか、のメモです。
svgrライブラリを利用したら簡単なのですが、素の?Reactの場合とかバージョン違いとかでちょいちょいやり方が違って少し右往左往したのでメモしておこうと思います。

基本は、公式ドキュメントの通りです。
https://react-svgr.com/docs/next/

optionsはnextの場合はnext.config.jsに追記していきます。
SVGタグの中にtitleタグをちゃんと入れたい場合は titleProp: true,titleId: 'filePath' を設定します。こんなかんじ。

module.exports = {
  webpack(config) {
    config.module.rules.push({
      test: /\.svg$/i,
      issuer: /\.[jt]sx?$/,
      use: {
        loader: '@svgr/webpack',
        options: {
          titleProp: true,
          titleId: 'filePath'
        }
      },
    })

    return config
  }
}

これで、例えば

import SampleIcon from '../icon/sample-icon.svg'

export const Icon = () => {
    return (
        <SampleIcon title="sample icon" titleId="sample_icon01" />
    )
}

とか書くと

<svg (中略) aria-labelledby="sample_icon01">
    <title aria-labelledby="sample_icon01">sample icon</title>
    /* svg tag本体 */
</svg>

と出力されます。


GutenbergなReactを見慣れているとNext.jsのスッキリ加減にうっとりしますね(較べてもしょうがないのですが)。svgrの中身マネッコして、Alternative Site Logoをリファクタリングできるといいなあ。

参照URL


この記事を書いた人