Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically loading Material-UI Icons in React

I'm trying to make React component that dynamically imports requested Material-UI icon, when the page loads. My solution presented here works, but it gives warning at compile time. Additionally it slows down the compilation of the project.

Any idea on how to do this properly? https://github.com/jurepetrovic/ordermanager_demo

The main logic is found in App.js, lines 5-10:

import React, { Component } from 'react';
import BarChartIcon from '@material-ui/icons/BarChart';

const MaterialIcon = ({ icon }) => {

  console.log("icon: " + icon);
  let resolved = require(`@material-ui/icons/${icon}`).default;
  return React.createElement(resolved);
}

class App extends Component {


  render() {

    return (
     <div>

        <MaterialIcon icon={"PowerSettingsNew"} />

     </div>
   );
  }
 }

export default App;

The warning it gives is this:

Compile warning

like image 584
Jure Avatar asked Sep 17 '19 20:09

Jure


1 Answers

I finally found the simplest solution to this problem:

  1. import all material icons from the package:

    import * as Icons from '@material-ui/icons'
    
  2. I assume you fetch your icon names from your api and finally you have something like this:

    var iconNamesArray = ["FitnessCenter","LocalDrink","Straighten"]
    
  3. Finally load your Icons like below:

    <div className="my-icons-wrapper-css">
      {
        iconNamesArray.map((el,ind)=>{
          let DynamicIcon = Icons[el]
          return(
             <DynamicIcon className="my-icon-css"/>
           );
       })
      }
    </div>
    

And your icons will appear in the screen.

like image 93
Mahdieh Shavandi Avatar answered Oct 15 '22 13:10

Mahdieh Shavandi