Search code examples
styled-components

Using Material Icons with Styled Components


Just started playing around with Styled Components. Is there a way to style third party icons such as Material Design Icons? This is the code I have so far but obviously it isn't working. Relavant code is below Content component Thanks!

const MaterialIcon = (props) => <i className="material-icons">account_balance</i>;

const Icon = styled(MaterialIcon)`
  background-color: green;
  font-size: 50px;
`;

const CheckThisOut = props => (
  <Wrapper>
    <Header>
      <h5>{props.title}</h5>
      <Icon />
    </Header>
    <Divider />
    <Content>
      <p>5% of all participants in this campaign were first time users.</p>
    </Content>
  </Wrapper>
);

export default CheckThisOut;

enter image description here


Solution

  • For the styled(AnyComp) notation to work AnyComp needs to accept the incoming className prop and attach it to a DOM node.

    For your example to work MaterialIcon has to use the passed in className, otherwise the styles are injected but no DOM node is targeted:

    const MaterialIcon = (props) => (
      <i className={`material-icons ${props.className}`}>account_balance</i>
    );
    
    // WORKS 🎉
    const Icon = styled(MaterialIcon)`
      background-color: green;
      font-size: 50px;
    `;
    

    See our documentation page about styling any component for more information!