Anna
Anna

Reputation: 89

React & MUI: Unable to style MUI Icon with makeStyles

I want to style mui Icons using className attribute, however it doesn't work. But when I'm applying inline styles it works as expected. I will have a few Icons in the component which I want to style the same way that's why I don't want to use inline styles and copy the same code several times. What am I doing wrong? Can someone please help?

import React from 'react';
import FacebookIcon from '@mui/icons-material/Facebook';
import TwitterIcon from '@mui/icons-material/Twitter';
import { makeStyles } from '@mui/styles';

const useStyles = makeStyles({
    root: {
        fontSize: '50px',
        margin: '10px',
        color: 'primary'
    }
});

const Links = () => {

    const classes = useStyles();

    return(
        <div>
            //this doesn't work
            <TwitterIcon className={classes.root} />

            //this works
            <FacebookIcon sx= {{ fontSize:'50px', margin:'10px', color:'primary' }} />  
        </div>
    );
}

export default Links;

Thank you

Upvotes: 1

Views: 1763

Answers (1)

Summer
Summer

Reputation: 1291

makeStyles is legacy API that relies on JSS, not emotion. It should not be used unless you are supporting older versions of Mui.

The recommended way is to either use styled or specify variants in the theme object.

import { styled } from '@mui/material'

const SocialMediaIcon = styled(Icon)(({ theme }) => ({
  fontSize: 50,
  margin: 10,
  color: theme.palette.text.primary,
}))

<SocialMediaIcon component={TwitterIcon} />
const theme = createTheme({
  components: {
    MuiIcon: {
      variants: [
        {
          props: { variant: 'social' },
          style: {
            fontSize: 50,
            margin: 10,
            color: 'primary',
          },
        },
      ],
    },
  },
})

<Icon variant="social" component={Instagram} />

Demo.

Upvotes: 1

Related Questions