Chapter 7: Using CSS with React
Inline Styles vs. External Stylesheets
There are two main approaches to styling React components with CSS:
- Inline Styles: You can apply styles directly to JSX elements using the "style" attribute. This approach is convenient for simple styling, but it can lead to less maintainable code as styles become scattered throughout your components.
- External Stylesheets: Here, you create separate CSS files containing your styles and link them to your React components using the <> tag in the HTML head section. This approach promotes better separation of concerns and keeps your styles organized.
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:
- The "Button" component accepts a "className" prop and a "text" prop.
- The button element's "className" is set to the value of the "className" prop, allowing the parent component to determine the button's style.
- The external stylesheet defines classes like ".primary-button" and ".secondary-button" that can be applied to buttons for different styles.
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.