React — Styling
Inline Styles
function StyledComponent() {
const style = {
color: 'blue',
fontSize: '20px',
padding: '10px'
};
return <div style={style}>Styled content</div>;
}
CSS Classes
function StyledComponent() {
return <div className="container">Styled content</div>;
}
CSS Modules
// styles.module.css
.container {
color: blue;
padding: 20px;
}
// Component.jsx
import styles from './styles.module.css';
function StyledComponent() {
return <div className={styles.container}>Styled content</div>;
}
Styled Components
import styled from 'styled-components';
const Container = styled.div`
color: blue;
padding: 20px;
&:hover {
background-color: lightgray;
}
`;
function StyledComponent() {
return <Container>Styled content</Container>;
}
Styling Examples
// Dynamic styles
function DynamicButton({ color, size }) {
const style = {
backgroundColor: color,
padding: size === 'large' ? '20px 40px' : '10px 20px',
fontSize: size === 'large' ? '18px' : '14px'
};
return <button style={style}>Click me</button>;
}
// Conditional styling
function TodoItem({ todo }) {
const className = todo.completed ? 'completed' : '';
return (
<li className={className}>
{todo.text}
</li>
);
}
// Theme provider
const ThemeContext = createContext('light');
function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={theme}>
<div className={`app ${theme}`}>
<ThemedButton />
</div>
</ThemeContext.Provider>
);
}
function ThemedButton() {
const theme = useContext(ThemeContext);
return (
<button className={`btn btn-${theme}`}>
Themed Button
</button>
);
}
Mini Practice
Write React code that:
- Uses inline styles
- Applies CSS classes
- Uses CSS modules
- Creates dynamic styles
Up Next
Next: Learn about CSS in React.
Related Topics
Frequently Asked Questions about Styling
What is Styling in React?
Styling is a fundamental concept in React. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Styling?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Styling.
Why is Styling important in React?
Styling is essential for React development. Understanding this concept will help you write better code and solve real-world problems more effectively.