SVGを使いたい時は、SVGRを使ってます。reactでSVG使うなら個人的には一番ラクな方法です。

手順1. FigmaでSVG書き出し
今回はFigma Communityから、material designのiconを使ってみます。
FigmaをDupliicateします https://www.figma.com/community/file/878585965681562011
使いたいアイコンをSVG形式で書き出します。画面右下のExportから。
手順2. SVGR Play Ground
扱うSVGが多ければSVGRを通して変換しても良いのですが、そんなに無いので、PlayGroundを都度利用します。 https://react-svgr.com/playground/ https://github.com/gregberge/svgr
PlayGroundなら、SVGファイルを貼り付けると、良い感じにreactコンポーネントとして吐き出してくれる。 typescriptなど必要なフラグをチェックしてコピー。
手順3. react
このままペーストすればOK。
実例+α
SVGをたまーに、すこしだけ追加するので、僕は svgr.tsx
にまとめてます。また、スタイルを調整できるように、少しだけ変更を加えるのがオススメ
- 流用できるようにinterfaceへとコピペ。
- svgのfill(色のこと)をcurrrentにしておく
// svgr.tsxinterface iconProps {props?: React.SVGProps<SVGSVGElement>svgRef?: React.Ref<SVGSVGElement>}export const IconA: React.FC<iconProps> = ({ props, svgRef }) => {return (<svgwidth="1em"height="1em"viewBox="0 0 48 48"fill="none"xmlns="http://www.w3.org/2000/svg"ref={svgRef}{...props}><path d="..." fill="current" /></svg>)}export const IconB: React.FC<iconProps> = ({ props, svgRef }) => {return (<svgwidth="1em"height="1em"viewBox="0 0 48 48"fill="none"xmlns="http://www.w3.org/2000/svg"ref={svgRef}{...props}><path d="..." fill="current" /></svg>)}
呼び出す時にはpropsに入れて渡せばOK
import { IconA } from './svgrexport const ComponentA: React.FC<ComponentAProps> = () => {return <IconA props={{ height: 38, width: 38, color: 'red' }} />}
↓参考書籍はこちら↓
