Styling is an essential part of building user interfaces.
In this lesson, you will learn multiple ways to apply styles in React and understand when to use each approach.
Styling Options in React
React does not enforce a single styling solution.
Common styling approaches include:
- Regular CSS files
- Inline styles
- Conditional class names
- CSS Modules (introductory concept)
Choosing the right method depends on project size and complexity.
Using Regular CSS Files
The simplest approach is using standard CSS files.
Example file structure:
- src/
- styles.css
Importing CSS into a component:
import "./styles.css";Using class names:
function Title() {
return <h1 className="title">Hello React</h1>;
}CSS files are global by default.
Inline Styles
Inline styles are written as JavaScript objects.
function Box() {
const style = {
backgroundColor: "lightblue",
padding: "16px",
borderRadius: "8px"
};
return <div style={style}>Styled Box</div>;
}Inline styles:
- Use camelCase properties
- Do not support pseudo-classes
- Are useful for dynamic styles
Conditional Styling
Styles often depend on state or props.
function Button({ isActive }) {
return (
<button className={isActive ? "btn active" : "btn"}>
Click
</button>
);
}This allows dynamic UI feedback.
Conditional Inline Styles
Inline styles can also be conditional.
function Status({ online }) {
return (
<p style={{ color: online ? "green" : "red" }}>
Status
</p>
);
}This is useful for simple visual changes.
CSS Modules (Intro)
CSS Modules scope styles locally to components.
Example file:
- Button.module.css
Using CSS Modules:
import styles from "./Button.module.css";
function Button() {
return <button className={styles.primary}>Click</button>;
}This prevents class name collisions in large projects.
Styling Best Practices
Recommended practices:
- Keep styles close to components
- Use meaningful class names
- Avoid overly complex inline styles
- Prefer CSS files or modules for large apps
- Be consistent across the project
Clean styling improves maintainability.
Common Styling Mistakes
Avoid:
- Mixing too many styling approaches
- Hardcoding styles everywhere
- Ignoring responsive design
- Using inline styles for everything
Consistency is key in UI development.
Summary
In this lesson, you learned:
- Different styling approaches in React
- How to use regular CSS files
- How inline styles work
- Conditional styling techniques
- Introduction to CSS Modules
- Styling best practices
In the next lesson, we will explore useEffect and lifecycle basics and learn how to handle side effects in React components.