CSS files are commonly used to style React components. All CSS features are supported and set up by default with Create React App.
Css Style file
/* Button.css */
.button {
background-color: blue;
color: white;
}
// Button.tsx
import "./Button.css";const Button = () => {
return <button className="button">Click me</button>;
};
Inline CSS styling
React elements using inline CSS can fully scope styles. However, inline styles lack some stylistic features. Example: :hover pseudo-class styling.
const Button = () => {
return (
<button style={{ backgroundColor: "blue", color: "white" }}>
Click me
</button>
);
};
CSS-in-JS Modules (Styled Components, Emotion, and Styled-jsx)
CSS-in-JS modules integrate well with React components, making them popular for styling React apps. They enable runtime style changes based on React props.
import styled from "styled-components";
const Button = styled.button`
background-color: blue;
color: white;
`;const App = () => {
return <Button>Click me</Button>;
};
CSS Modules
CSS Modules scope styling to one component. It's an excellent approach to organise styles, minimise class name clashes (common in large projects), and offer shared styles to numerous components.
/* Button.module.css */
.button {
background-color: blue;
color: white;
}// Button.js
import styles from "./Button.module.css";const Button = () => {
return <button className={styles.button}>Click me</button>;
};