React and CSS

There are several ways to use CSS within React applications.

Inline CSS

We can create a structural type as a variable or const (more likely), for example

const style = {
  background: 'red',
  width: '100px',
  color: 'white'
};

export const MyStyledDiv: React.SFC<{}> = ({
}) => <div style={style}>Hello World</div>

In this case we’re using React.SFC just to reduce the code to a minimal, but fully fledged Components would work in the same way within the render function.

Style based components

With style based components we in essence create a component from the style using the back tick syntax along with the prefix styled.{element type}, so for example

const DivStyle = styled.div`
  background: red;
  width: 100px;
  color: white;
`;

export const MyStyledDiv: React.SFC<{}> = ({
}) => <DivStyle>Hello World</DivStyle>

CSS Modules

We can create separate files for our css (known as CSS Module StyleSheets).

In this case we create a .css file, for example MyStyledDiv.module.css which uses standard CSS syntax, so for example here my file

.myDivStyle {
    background-color: red;
    width: 100px;
    color: white;
}

Now in our component we import the CSS in much the same way as importing components, for example

import styles from './MyStyledDiv.module.css';

export const MyStyledDiv: React.SFC<{}> = ({
}) => <div className={styles.myDivStyle}>Hello World</div>

These style sheets are locally scoped to the component which imports them which helps us to reduce possible name clashes etc.

Standard CSS files

In this case we have standard CSS files, here we have a file named myStyleDiv.css with the following (which is the same as our module.css contents)

.myDivStyle {
    background-color: red;
    width: 100px;
    color: white;
}

Now we again import the CSS like this

import './MyStyledDiv.css';

export const MyStyledDiv: React.SFC<{}> = ({
}) => <div className="myDivStyle">Hello World</div>

Emotion

We can also use third party library’s such as emotion.

Here’s the same example using emotion

const DivStyle = styled.div(props => ({
  background: 'red',
  width: '100px',
  color: 'white'
}))

export const MyStyledDiv: React.SFC<{}> = ({
}) => <DivStyle>Hello World</DivStyle>