How can I dynamically load an icon using its snake_case name (React, material-ui)

女生的网名这么多〃 提交于 2020-02-01 09:12:30

问题


Normally I'd use material-ui icons by importing them directly per the material-ui instructions.

But I have a text tag, which is the actual icon name (like calendar_view_day) and need to get and render an icon component from it dynamically.

How can I something like:

render() {
  return (
    <Icon name="calendar_view_day" color="primary" />
  )
}

Instead of:

render() {
  return (
    <CalendarViewDay color="primary" />  // Imported by name
  )
}

回答1:


OK, so I massively overthought this.

Correct answer

Turns out material-ui includes an icon component that allows you to do this... and it converts names itself, so accepts snake, pascal and other variants. BEWARE this will massively increase bundle size, as pointed out in the comments. If you're bundle size constrained, you'll have to take a different approach of serving the icon SVGs from somewhere!

import Icon from '@material-ui/core/Icon'

...

render() {
  return (
    <Icon>{props.iconName}</Icon>
  )
}

Previous answer (working but massive overkill)

Create function to:

  • convert snake_case to PascalCase
  • Handle special cases reported in the material-ui icons documentation

...Then use the material-ui Icon component.

Here's the code:

import Icon from '@material-ui/core/Icon'

function upperFirst(string) {
  return string.slice(0, 1).toUpperCase() + string.slice(1, string.length)
}

function fixIconNames(string) {
  const name = string.split('_').map(upperFirst).join('')
  if (name === '3dRotation') {
    return 'ThreeDRotation'
  } else if (name === '4k') {
    return 'FourK'
  } else if (name === '360') {
    return 'ThreeSixty'
  }
  return name
}

...

render() {
  const iconName = fixIconNames(props.iconName)
  return (
    <Icon>{props.iconName}</Icon>
  )
}


来源:https://stackoverflow.com/questions/56369444/how-can-i-dynamically-load-an-icon-using-its-snake-case-name-react-material-ui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!