Sage-Code Laboratory
index<--

Chapter 7: Using CSS with React

Chapter 7 explores how to style your React components with CSS. Styling is essential for creating a visually appealing and user-friendly application.

Inline Styles vs. External Stylesheets

There are two main approaches to styling React components with CSS:

Recommendation: Generally, using external stylesheets is preferred for maintainability and scalability, especially for larger projects.

Applying CSS Classes to Components

You can apply CSS classes to your React components using the "className" attribute in JSX. This allows you to define styles in your external stylesheet and associate them with specific components or elements within your components.


import React from 'react';

    function Button(props) {
    return (
        <button className={props.className}>{props.text}</button>
    );
}

CSS must be stored in a separated file. Here are the rules:


/* stylesheet.css */

.primary-button {
    background-color: blue;
    color: white;
    padding: 10px 20px;
    border: none;
    border-radius: 5px;
}

.secondary-button {
    background-color: gray;
    color: black;
    padding: 5px 10px;
    border: 1px solid #ccc;
    border-radius: 3px;
}

In this example:

Using CSS Modules for Component-Scoped Styling

CSS Modules is a technique that helps prevent style conflicts by generating unique class names for each component. This ensures styles defined for a specific component are only applied to that component, avoiding unintended side effects on other parts of your application.

There are various tools and libraries that support CSS Modules in React development. We'll explore specific tools and their usage in a future chapter.

By effectively combining these techniques, you can achieve a well-styled and maintainable React application.


Read next: Using Bootstrap