Fred
Fred

Reputation: 645

material-UI: Unable to set Color of SVG Icon inside Tab

Have the following inside a react class render():

import {blue900} from 'material-ui/styles/colors';
import {Tabs, Tab} from 'material-ui/Tabs';
import SocialPeople from 'material-ui/svg-icons/social/people';

var myClass = React.createClass({
   render: function() {
     return (
      <Tabs>
        <Tab icon={<SocialPeople color={blue900} />}/>
      </Tabs>
     );
   }
});

The SVG icon color is ignored above, whereas it works below:

var myClass = React.createClass({
   render: function() {
     return (
        <SocialPeople color={blue900} />
     );
   }
});

Can anyone explain this? How to set icon color inside the tab element?

Upvotes: 1

Views: 4358

Answers (1)

JiN
JiN

Reputation: 828

It seems like this is not possible at the moment without changing the library. I believe it's a bug. I had a hard time finding a solution to this. Then I just had a look at the code.

What I found out is that when an icon element is passed to Tab component, the props of the Tab component are changed including the style that you pass. So it makes a copy of the icon but with different props and styles and renders that.

if (icon && React.isValidElement(icon)) {
  const iconProps = {
    style: {
      fontSize: 24,
      color: styles.root.color,
      marginBottom: label ? 5 : 0,
    },
  };
  if (icon.type.muiName !== 'FontIcon') {
    iconProps.color = styles.root.color;
  }
  iconElement = React.cloneElement(icon, iconProps);
}

So the color that you send is neglected and it takes color from the MuiTheme.

https://github.com/callemall/material-ui/blob/master/src/Tabs/Tab.js

Have a look at the code. Lines 5 to 25 and 110 to 126..

So you will need to change the library to get the color. Just follow these steps..

  1. Open the file node_modules/material-ui/Tabs/Tab.js
  2. Go to line 128 which reads

iconProps.color = styles.root.color

and replace it with this

   if (icon.props) {
      if (icon.props.style && icon.props.style.color) {
        iconProps.color = icon.props.style.color;
      } else if (icon.props.color) {
        iconProps.color = icon.props.color;
      } else {
        iconProps.color = styles.root.color;
      }

      if (icon.props.hoverColor) {
        iconProps.hoverColor = icon.props.hoverColor;
      }
    }

That's it.. Now your icon element should be something like this

<SocialPeople style={{ color: 'red' }} />

Upvotes: 2

Related Questions