Skip to content

CSS in JS

styled components logo

Placing the css to style components next to the code (within the JS) makes it much easier to manage and understand, compared to placing the css in a separate file. There are many options to do this, including a built in styling system for Material-UI, however I find styled-components to be the best.

Styled-components is installed via npm,

npm install --save styled-components
npm install --save-dev @types/styled-components

which installed 5.2.1.

Normalizing

Normalize css logo

Each browser applies differing css styles to elements meaning that it is possible that your pages will look different in each browser making it harder to have a correct and consistent product. These differences can be normalized using normalize.css via the styled-normalize package,

npm install --save styled-normalize

which installed 8.0.7.

It is used by adding to the frontend/src/App.tsx as the first child of the <StylesProvider> element,

import { Normalize } from "styled-normalize";
...

const App = () => {
  ...
  return (
    <>
      <Normalize />
      ...
    </>
  );
}

Theming

Styled-components allows for themes to be used, which is helpful as they provide a singular location to define the colour palette, spacing, etc... A theme is an associate array that maps any named property to a value, which in order to work with Typescript requires the following in frontend/src/styled.d.ts, (assuming you export a theme from frontend/src/theme.ts - see Material-UI),

import {} from "styled-components";
import theme from "theme";

declare module "styled-components" {
  type Theme = typeof theme;
  export interface DefaultTheme extends Theme {}
}