Styling in React
Inline Styles
function Heading() {
return <h1 style={{ color: 'blue', fontSize: '24px' }}>Title</h1>;
}
Dynamic, but it does not support pseudo-classes or media queries.
CSS Modules
Create a .module.css file, and React will scope class names locally.
/* Heading.module.css */
.title { color: blue; font-size: 24px; }
import styles from './Heading.module.css';
function Heading() { return <h1 className={styles.title}>Title</h1>; }
CSS-in-JS (styled-components)
import styled from 'styled-components';
const Button = styled.button`
background: ${p => p.primary ? 'blue' : 'gray'};
color: white; padding: 8px 16px; border-radius: 4px;
&:hover { opacity: 0.8; }
`;
Tailwind CSS
function Card({ title, desc }) {
return (
<div className="rounded-lg bg-white p-6 shadow-md">
<h2 className="text-xl font-bold">{title}</h2>
<p className="mt-2 text-gray-600">{desc}</p>
</div>
);
}
CSS Frameworks (MUI / Bootstrap)
import Button from '@mui/material/Button';
function App() { return <Button variant="contained">Click</Button>; }
Best Practices
| Approach | Best For |
|---|---|
| Inline | Simple dynamic styles |
| CSS Modules | Vanilla CSS projects |
| styled-components | Reusable components, theming |
| Tailwind | Rapid prototyping |
| MUI/Bootstrap | Complete UI framework |
Stay consistent with one approach per project. Next chapter: Fragments & Portals.