Styling in React JS

How many types of styles do we have in React JS?

Inline Style

  1. Use the style attribute directly on your elements.
  2. Syntax is a bit different from basic CSS — you need to use an object with camelCase properties.

Example:

<div style={{ color: 'blue', fontSize: '16px' }}>Hello World!</div>


External Style

  1. Create a separate CSS file.
  2. Import that file into your component.

Example:

.container {
background-color: lightgray;
padding: 20px;
}


Then import in your React component:

import './styles.css';


CSS Modules

  1. Similar to external CSS files.
  2. But ensures that styles are locally scoped to a specific component — no global style leakage.

Example:

/* MyComponent.module.css */
.container {
background-color: lightgray;
padding: 20px;
}


Then use in your component:

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

<div className={styles.container}>Hello World!</div>


Styled Components

  1. A popular library that allows you to write CSS inside JavaScript components.
  2. This approach is called CSS-in-JS.

Example:

import styled from 'styled-components';

const Button = styled.button`
background-color: ${props => props.primary ? 'blue' : 'gray'};
color: white;
padding: 10px 20px;
border: none;
`;


External CSS Libraries / Frameworks

You can also use third-party CSS libraries in your React project:

  1. Material-UI
  2. React Bootstrap
  3. Tailwind CSS