lucas_dev
lucas_dev

Reputation: 97

Passing dynamic color to Material-UI Icon

The properties (like font awesome classes, color as HUE) of the icons I want to display are defined in a JSON file like:

"users": {"icon":"fas fa-users",
            "iconcolor":"green"}

Then for each icon, I tried this without success.

<Icon className={icon} style={{ color: {iconcolor}[500] }} fontSize="small"></Icon>

It compiles but icons are still displayed in primary style. Am I doing something wrong here ? How to make work ?

Upvotes: 1

Views: 5009

Answers (2)

Sachin Vishwakarma
Sachin Vishwakarma

Reputation: 884

first import the color from material ui

import purple from '@material-ui/core/colors/purple';
import green from '@material-ui/core/colors/green;

var selectedColor = {iconcolor} === 'green' ? green : purple
<Icon className={icon} style={{ color: {selectedColor}[500] }} fontSize="small"></Icon>

you can use switch case as well. or you can store the color code in the user data.

Upvotes: 1

adir abargil
adir abargil

Reputation: 5745

instead of :

<Icon className={icon} style={{ color: {iconcolor}[500] }} fontSize="small"></Icon>

you should pass the actual color...

<Icon className={icon} style={{ color: iconcolor}} fontSize="small"></Icon>

this is only if the default css color naming are supporting this color as a name.. you can additionally send a hex (#ffffff for white for example) color or rgb colors:

<Icon className={icon} style={{ color: 'rgb(255,0,0)'}} fontSize="small"></Icon>

Note: the green[500] you see in this docs is using material-ui's library of colors which generates a string like i showed you...

Upvotes: 0

Related Questions