CSS in JS [REACT]

Hi!

I’m starting to use Material-UI for a weather react app i’m working on. I’m very curious as to why people wanna write CSS inside the Js file and use it! like this:

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';

const useStyles = makeStyles({
  root: {
    background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
    border: 0,
    borderRadius: 3,
    boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
    color: 'white',
    height: 48,
    padding: '0 30px',
  },
});

export default function Hook() {
  const classes = useStyles();
  return <Button className={classes.root}>Styled with Hook API</Button>;
}

from here: https://material-ui.com/styles/basics/#material-ui-styles

I’d rather just keep all that in my CSS file.

Am I missing anything?

It’s just preference, and a bit of a Holy War topic.

I use Material UI, and I also prefer separate CSS files (well, SCSS).

But really, it doesn’t matter. Pick a pattern you like and stay consistent.

Yup, this is a highly debated topic. Advocates of css-in-js are often advocates of “functional programming”, and disdain the concept of inheritance which is found even in javascript and React but more recently has been shied away from. Pure css has inheritance, but in order to follow functional programming principles, you can use styling frameworks like material ui.

The main selling point of material ui, is that you can create styles that are privatized to the react component you are writing. If you are using pure css there is a chance that the styles you write for your component can influence the styles of other modules.

The CSS rules there are explicitly scoped to a specific component. You can’t do that with just CSS, CSS is global. It allows you to conditionally apply styles (normal way in CSS is to have different classes then change those to change the styling). It’s normally more maintainable, which is an issue with just CSS (which is extremely hard to maintain in larger projects). It normally produces less CSS – it can be easily analysed to strip unused rules because it’s explicitly tied to the HTML (on the other hand, CSS is implicitly tied to the HTML).

It’s generally a good thing, nice to use. Both approaches are completely valid and have their upsides and downsides; CSS-in-JS makes some thing that are hard in just CSS much easier, but it also adds an extra shedload of complexity

Alright!
Thanks for the input then!

I think the whole idea is for big teams only. I’ve been using one CSS file and doing all my CSS there. Just like a normal one page website that you’d do.