2
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 + Material UIで動的にMaterialアイコンを表示する

Last updated at Posted at 2021-06-20

Material UIのアイコンを入力とか、データループとかから動的に作成したかった

やりかた

サイドバーのデータを表示する例

import * as Icons from '@material-ui/icons/'

const datas = [
    {
        icon: 'Home',
        title: 'ホーム',
        to: '/home',
    }
]

function Sidebar(){
  return (
    <ul>
      {datas.map((data, index) => (
        <li>{React.createElement(Icons[data.icon])}</li>
      ))}
    </ul>
  )
}

import * as Icons from '@material-ui/icons/'
モジュールのコンテンツすべてをインポートしています。参考

あとは、データをループしてReact.createElementでReact要素で対象のアイコンを作成しています

ちなみにTSでやる際はIcons[data.icon]でエラー吐いたので下記のように、Materialアイコンのkeyを使用するようにしました。

import * as Icons from '@material-ui/icons/';

interface route {
  icon: keyof typeof Icons;
  title: string;
  to: string;
}

const datas: route[] = [
    {
        icon: 'Home',
        title: 'ホーム',
        to: '/home',
    }
]
2
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
2
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?