Styling in React.js
1. Inline Styles
In React, inline styles are written as a JavaScript object with camelCase properties. This method can be useful for dynamically setting styles based on component state or props.
Example:
function Button() {
const buttonStyle = {
backgroundColor: 'blue',
color: 'white',
padding: '10px 20px',
border: 'none',
borderRadius: '5px'
};
return ;
}
Key points:
style
attribute.backgroundColor
instead of background-color
).lineHeight
or zIndex
.
2. CSS Stylesheets
The traditional way of styling web applications is by linking a CSS stylesheet. In React, you can simply import a CSS file into your component or your main file.
Example:
Button.css:
.button {
background-color: blue;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
}
Button.js:
import './Button.css';
function Button() {
return ;
}
className
attribute (instead of class
) is used to apply the CSS class to an element.
3. CSS Modules
CSS Modules are a way to locally scope CSS by automatically creating unique class names. This prevents class name collisions and allows you to manage styles more modularly.
Example:
Button.scss:
$primary-color: blue;
.button {
background-color: $primary-color;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
}
Button.js:
import './Button.scss';
function Button() {
return ;
}
In this example, SCSS allows the use of variables ($primary-color) and other SASS features to improve the styling workflow
7. External UI Libraries
React supports various external UI libraries that come pre-styled with themes and components, making development quicker and more visually consistent.
Some popular libraries include:
react-bootstrap
.
npm install @mui/material @emotion/react @emotion/styled
import * as React from 'react';
import Button from '@mui/material/Button';
function App() {
return ;
}
These libraries provide a wide range of ready-made components and styles, making them a great option for rapid development.
Conclusion
React provides multiple ways to style your applications, ranging from simple inline styles to more advanced techniques like CSS Modules, Styled Components, and CSS-in-JS. The method you choose will depend on the project requirements, scalability, and personal preference. For larger projects, solutions like CSS Modules, Styled Components, or external UI libraries can provide better scalability and maintainability.