Styling in React

CSS in React

CSS in React is similar to the standard CSS used with JavaScript. A class (className in React) attribute is assigned to an HTML element(JSX) styled in a CSS file. This approach also allows us to write styles directly in JSX elements just like in HTML files. This approach is called inline styling. The main difference is the styles are written as objects in React. Inline styling in React is flexible as we can define styles based on certain conditions.


//Button.jsx

import './Button.css';
return (
const Button = () => {
  <button className="btn" style={{ color: 'blue' }}> Click </button>
  )
}

//Button.css

.btn {
  background-color: 'black';
}

CSS Modules in React.

CSS Modules in React is an advanced styling approach. The CSS file remains the same but the file name is changed. For example: "Button.css" is changed to "Button.module.css". This is done to make use of CSS styles as modules in JSX. Instead of placing the CSS styles in the className as strings in JSX, we place the CSS styles as objects.

//Button.jsx

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

return (
const Button = () => {
  <button className={styles.btn}> Click </button>
  )
}

//Button.module.css
.btn {
  background-color: 'black';
}

There is a shortcoming to this approach. Say we have a module(CSS class) described with a hyphen: "button-small". The styles contained in the class would not be accessible as the class would not be recognized as a module in React.

The advantage of this approach is that undefined styles cannot go unnoticed. An error would be prompted in such a case unlike the CSS in React approach.

Styled Components in React

Styled Components is one of the most popular CSS in JS approach to styling in React. It comes as a dependency in JavaScript, so it must use a package manager like npm or yarn for installation. Click to see how. Styled Components are styles described as React Components. The Components are created and assigned styles using template literals. They work the same way as React Components.

//Button.jsx

import styled from 'styled-components'; //do this after installation

const StyledButton = `
  color: white;
  background-color: black;
  border-radius: 8px;
`;

const Button = () => {
return(
  <StyledButton> Click </StyledButton>
  )
}

Styled Components promote reusability, it is also less prone to errors that might occur as a result of assigning the same class to multiple elements.