Styling in React

Sep 7, 2024

Although, there are many possible ways you can use styles in React application, following are the general categories to choose from.

  1. Default: React supports the default styling via class. Actually, via className. Or you can write the inline styles. But, you need to define it as an object and kebab-case converted to camelCase for the CSS properties whereas values must be defined as string. Event further you can use framework classes such as from Bootstrap or Tailwind. Some frameworks have React component wrapper around it such as react-bootstrap. But, still internally they use className.
// React component with class/className 
// (true for Bootstrap or Tailwind).
const Component = () => {
  return (
    <h1 className="title">Header</h1>
  )
};
// React component with inline styles.
const Component = () => {
  return (
    <h1 style={{ fontSize: "14px", paddingTop: "14px" }}>
      Header
    </h1>
  )
}
// React component with inline styles as style object.
const headerStyles = {
  fontSize: "14px",
  paddingTop: "14px",
};

const Component = () => {
  return (
    <h1 style={headerStyles}>Header</h1>
  )
}
  1. CSS Modules: This is not the default one that you can write within normal HTML/CSS. But, React provide the supports for it when you create an application using create-react-app. If you have a component in Component.jsx then you can define a styles for it in Component.module.css (here .module.css is important) and then you can import whole styles as JavaScript object and use the classes defined within this Component.module.css. This make sure that styles don’t have the side-effect on other components and correctly scoped.
  2. CSS-in-JS: People like the idea of inline style in React as you can define it as an object and you have autocomplete and suggestion for it. So, developers extend it further and make some good changes on top of it by making a style as component. Examples are styled-components, Emotion, etc.
Tags: react