</>
Skip to content
React lessons (34/47)

React — CSS

Global CSS

// index.css
import './index.css';

function App() {
    return <div className="App">Hello</div>;
}

CSS Modules

// Button.module.css
.button {
    padding: 10px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.primary {
    background-color: blue;
    color: white;
}

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

function Button({ children, variant = 'primary' }) {
    return (
        <button className={`${styles.button} ${styles[variant]}`}>
            {children}
        </button>
    );
}

CSS-in-JS

import styled from 'styled-components';

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

function Button() {
    return <StyledButton primary>Click me</StyledButton>;
}

CSS Examples

// Responsive design
function ResponsiveLayout() {
    return (
        <div className="layout">
            <aside className="sidebar">
                <nav>Sidebar</nav>
            </aside>
            <main className="content">
                <p>Main content</p>
            </main>
        </div>
    );
}

// CSS
.layout {
    display: flex;
}

.sidebar {
    width: 250px;
    background-color: #f5f5f5;
}

.content {
    flex: 1;
    padding: 20px;
}

@media (max-width: 768px) {
    .layout {
        flex-direction: column;
    }

    .sidebar {
        width: 100%;
    }
}

// Animations
function AnimatedComponent() {
    const [isVisible, setIsVisible] = useState(false);

    return (
        <div className={`fade-in ${isVisible ? 'visible' : ''}`}>
            <button onClick={() => setIsVisible(!isVisible)}>
                Toggle
            </button>
            <p>Animated content</p>
        </div>
    );
}

// CSS
.fade-in {
    opacity: 0;
    transition: opacity 0.3s ease;
}

.fade-in.visible {
    opacity: 1;
}

Mini Practice

Write React code that:

  1. Uses global CSS
  2. Implements CSS modules
  3. Creates responsive layouts
  4. Adds CSS animations

Up Next

Next: Learn about Bootstrap in React.

Related Topics

Frequently Asked Questions about CSS

What is CSS in React?

CSS is a fundamental concept in React. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn CSS?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn CSS.

Why is CSS important in React?

CSS is essential for React development. Understanding this concept will help you write better code and solve real-world problems more effectively.