Styling in React JS
How many types of styles do we have in React JS?
Inline Style
- Use the
style
attribute directly on your elements. - Syntax is a bit different from basic CSS — you need to use an object with camelCase properties.
Example:
<div style={{ color: 'blue', fontSize: '16px' }}>Hello World!</div>
External Style
- Create a separate CSS file.
- Import that file into your component.
Example:
.container {
background-color: lightgray;
padding: 20px;
}
Then import in your React component:
import './styles.css';
CSS Modules
- Similar to external CSS files.
- But ensures that styles are locally scoped to a specific component — no global style leakage.
Example:
/* MyComponent.module.css */
.container {
background-color: lightgray;
padding: 20px;
}
Then use in your component:
import styles from './MyComponent.module.css';
<div className={styles.container}>Hello World!</div>
Styled Components
- A popular library that allows you to write CSS inside JavaScript components.
- This approach is called CSS-in-JS.
Example:
import styled from 'styled-components';
const Button = styled.button`
background-color: ${props => props.primary ? 'blue' : 'gray'};
color: white;
padding: 10px 20px;
border: none;
`;
External CSS Libraries / Frameworks
You can also use third-party CSS libraries in your React project:
- Material-UI
- React Bootstrap
- Tailwind CSS