Ananda Pramono
Ananda Pramono

Reputation: 1009

Using SCSS In Material UI React directly

I have some issue using scss directly in material ui, because not all styles are applied. Tried to use makeStyle, but because I use class component, it gives warning about invalid hook call.

The style :

.table-header {
  background-color: #005CAA; //only this style works
  color: white;
  font-weight: bold;
  text-align: center;
}

I call in in TableCell component from Material UI

 <TableCell className="table-header">Invoice Number</TableCell>

For the scss file, I import it in parent component App.tsx, or I need to import the file directly in the Table component? Thx

Upvotes: 2

Views: 19497

Answers (3)

Viraj Singh
Viraj Singh

Reputation: 2329

I follow the makeStyles approach as it's recommended way of overriding the material-ui styles, else you'd have to use !important in your css/scss files to override the material-ui styles. https://mui.com/styles/basics/

// component file
import React from 'react';
import { TextLineStyles } from './styles';

export default function TextLine({ text }) {
  const classes = TextLineStyles()
  return <div className={classes.root}>
    <div data-title="line" >
      <div data-title="text">
        {text}
      </div>
    </div>
  </div>
}



// style.js
import { makeStyles } from "@material-ui/core/styles";

export const TextLineStyles = makeStyles(theme => ({
    root: {
        '& [data-title="line"]': {
            borderTop: `1px solid lightgray`,
            '& [data-title="text"]': {
                color: 'red' // scss like nesting
            }
        }
    }
}));

Upvotes: 2

Juan Gil
Juan Gil

Reputation: 79

I am not sure if it is the best practice, in fact thats why I ended up in this post. Here it explain how to use scss with material-ui: https://www.markmakesstuff.com/posts/mui-css-modules

  1. "Just install node-sass"
  2. "if you're working with an app you initialized with a script like create-react-app, you are in luck. No webpack edits necessary. Just give your module a name that ends with ".module.scss"" OTHERWISE 2') You need to "make some minor edits to your webpack config"
  3. "You can then import your module with a name then use that to refer to your classes when writing your fancy JSX"

Upvotes: 1

Michael
Michael

Reputation: 1872

If you want to use CSS/SCSS class in MUI component, you should import the file directly in the Table component. But, it's not good to use SCSS with MUI component, you should use makeStyles or withStyles to style the MUI component.

Upvotes: 0

Related Questions