The Ultimate Guide to Styling in React
Setting up Your React Application
Before we dive into styling, let’s set up a demo React application using Create React App (CRA). This will give us a basic application to work with.
npx create-react-app my-app
cd my-app
npm start
Styling React Components with Inline Styling
Inline styling is a simple way to add styles to a React component. You can use the style
attribute to pass an object with CSS properties as key-value pairs.
import React from 'eact';
function InlineStylingExample() {
return (
<div
style={{
backgroundColor: 'blue',
padding: '20px',
fontSize: '24px',
color: 'white'
}}
>
This is an example of inline styling
</div>
);
}
Using Styled Components
Styled components is a popular library that allows you to write CSS-in-JS. You can create reusable UI components with custom styles.
import React from 'eact';
import { styled } from 'tyled-components';
const StyledDiv = styled.div`
background-color: blue;
padding: 20px;
font-size: 24px;
color: white;
`;
function StyledComponentsExample() {
return (
<StyledDiv>
This is an example of styled components
</StyledDiv>
);
}
CSS Modules
CSS Modules is a feature that allows you to write CSS files that can be imported as JavaScript modules. This approach provides a clear separation of concerns between CSS and JavaScript code.
/* styles.css */
.container {
background-color: blue;
padding: 20px;
font-size: 24px;
color: white;
}
import React from 'eact';
import styles from './styles.css';
function CssModulesExample() {
return (
<div className={styles.container}>
This is an example of CSS Modules
</div>
);
}
Other Styling Options
In addition to the above methods, there are other ways to style React components, including:
- CSS-in-JS libraries like Emotion and Glamor
- Pre-processors like Sass and Less
- Utility-first frameworks like Tailwind CSS
Each approach has its own strengths and weaknesses, and the choice ultimately depends on your project’s specific needs and requirements.