In React, there are several ways to apply CSS to your components, each with its own advantages. Here are the most common methods:
1. Inline Styles
Inline styles are defined directly within the component using the style
attribute. The styles are written as an object, where the property names are camelCased versions of the CSS properties.
import React from 'react';
//MyComponent.jsx
export default function MyComponent() {
const style = {
color: 'green',
backgroundColor: 'yellow',
padding: '5px',
borderRadius: '3px'
};
return <div style={style}>Hello World text with inline styles!</div>;
}
2. CSS Stylesheets
You can use traditional CSS stylesheets by importing them into your React component. This is the most straightforward way to style your components.
CSS File (styles.css)
.my-class {
color: 'green',
backgroundColor: 'yellow',
padding: '5px',
borderRadius: '3px'
}
React Component
import React from 'react';
import './styles.css';
//MyComponent.jsx
export default function MyComponent() {
return <div className="my-class">This is styled with a CSS stylesheet!</div>;
}
3. CSS Modules
CSS Modules allow you to write CSS that is scoped locally to the component. This prevents conflicts with other styles and ensures that styles are only applied to the component they are intended for.
CSS Module (styles.module.css)
.my-class {
color: 'green',
backgroundColor: 'yellow',
padding: '5px',
borderRadius: '3px'
}
React Component
//CSSModulesComponent.jsx
import React from 'react';
import styles from './styles.module.css';
export default function CSSModulesComponent() {
return <div className={styles.myClass}>This is styled with CSS Modules!</div>;
}