React: How to use CSS in React

In this article I will describe two ways to use CSS in React.

Option 1: Inline

Define CSS styles ‘inline’ inside React. This uses the props key ‘style’, which uses a dictionary to define all of the CSS attributes. However, these CSS attributes have differences from normal CSS. For example,
1. The attribute names must be in camelCase, so the CSS attributeĀ font-familywould be changed to fontFamily.
2. The value portion of each attribute must be a string (surrounded by single quotes).
3. Each key-value pair is followed by a comma (since it is just another key-value pair inside the styles dictionary)

Here is what the React code with inline styles looks like:

function cell(props) {
  return React.createElement(
    'div', 
    {
      style: {
        justifyContent: 'center',
        alignItems: 'center',
        display: 'flex',
        fontFamily: 'Arial',
        fontSize: '3rem',
        fontWeight: 'bold',
        background: 'white'
      },
      id : props.number,
      onClick: props.onClick
    },                 
  )
}

Note: Here is the syntax that you would use when using JSX. Notice the double curly braces:

<h1 style={{fontFamily:"Arial"}}>React Tic-Tac-Toe</h1>

 

Option 2: CSS

Instead of defining the styles ‘inline’ as shown above, you can use standard CSS. For example:

.cell {
  justify-content: center;
  align-items: center;
  display: flex;
  font-family: Arial;
  font-size: 3rem;
  font-weight: bold;
  background: white;
}

In the React code, all we need to use this CSS class is a prop called className.

className: "cell"

(We don’t need the style prop.)
Here is what the React code looks like without the inline styles:

function cell(props) {
  return React.createElement(
    'div', 
    {
      className: "cell",
      id : props.number,
      onClick: props.onClick
    },                 
  )
}