Styling Components with External CSS
メニューを表示するにはスワイプしてください
While inline styles are useful for small or dynamic styling, most real applications rely on external CSS files. This approach keeps styles separate from component logic and makes them easier to manage as projects grow.
React supports external CSS out of the box. You can write regular CSS and apply it to components using class names, just like in traditional web development.
Creating an External CSS File
First, create a CSS file and define your styles:
/* styles.css */
.title {
font-size: 32px;
font-weight: 700;
color: rebeccapurple;
}
This CSS file contains a simple class that can be reused across components.
Importing CSS into a Component
To use the styles, import the CSS file into your component file:
import "./styles.css";
const App = () => (
<>
<h1 className="title">App title</h1>
</>
);
In React, the class attribute is written as className because class is a reserved keyword in JavaScript.
How External CSS Works in React
CSS files are applied globally by default. Any component can use a class defined in an imported CSS file. Styles behave the same way as in standard HTML and CSS. This makes external CSS familiar and easy to use, especially for developers coming from traditional web development.
When to Use External CSS
External CSS is a good choice when:
- Styles are shared across multiple components;
- Layouts become more complex;
- You want a clear separation between structure and styling.
For larger projects, external CSS often leads to cleaner and more maintainable code.
1. How do you apply a CSS class to an element in React?
2. What is true about external CSS in React?
フィードバックありがとうございます!
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください