Home » Using CSS In React

Using CSS In React

Using CSS In React

Introduction

CSS (Cascading Style Sheets) is a fundamental technology used for styling web pages, including those built with React. In React applications, CSS is used to control the visual presentation and layout of components, allowing developers to customize the appearance of their user interfaces.

There are several approaches to styling React components:

Inline Style

React supports inline styles, where CSS styles are defined directly within the JSX code using JavaScript objects. Inline styles are specified using the style attribute and provide a way to apply dynamic styles based on component state or props.

const MyComponent = ({ isHighlighted }) => {
  const dynamicStyles = {
    backgroundColor: isHighlighted ? 'yellow' : 'transparent',
    color: isHighlighted ? 'black' : 'inherit',
  };

  return (
    <div style={dynamicStyles}>
      {/* Component content */}
    </div>
  );
};
JSX

External CSS File

Developers can create separate CSS files and import them into their React components using the import statement. This traditional approach allows for separation of concerns, where CSS styles are maintained separately from the component logic.

// Example of importing an external CSS file in a React component
import './styles.css';

const MyComponent = () => {
  return (
    <div className="my-component">
      {/* Component content */}
    </div>
  );
};
JSX

CSS Modules

CSS modules prevent class name clashes by appending a unique identifier to each class name. This ensures that styles are scoped to their respective components. However, it’s still possible to have multiple classes with the same name in different modules. CSS modules will generate unique class names to avoid conflicts. They promote modularity, encapsulation, and reusability. By leveraging CSS modules, you can write cleaner and more maintainable styles in your React projects.

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

const MyComponent=()=>{
  return(
  <>
  <div className={styles.container}></div>
  </>
  );
}
JSX
./styles.module.css file

.container{
  width:20em;
  height:10vh;
  background-color:rgba(0,150,100,0.4);
}
JSX

Conclusion

Styling React components is essential for defining the look and feel of applications. Various approaches, each with unique advantages, include inline styles for dynamic, component-specific styling, and external CSS files for separating concerns. CSS Modules offer scoped styles to prevent conflicts and enhance modularity, while CSS-in-JS libraries like styled-components and Emotion provide dynamic styling and theming capabilities. CSS frameworks like Bootstrap and Material-UI accelerate development with pre-defined styles. Choosing the right method depends on project needs, application scale, and team workflow, enabling the creation of aesthetically pleasing, maintainable, and scalable React applications.

Frequently Asked Questions