Styling
Styling Components in React
Β
In React, components are commonly styled using CSS classes through the className attribute. Since JSX supports JavaScript expressions, React allows multiple styling approaches. Some popular styling methods include:
CSS Stylesheets β Traditional CSS files used with className
Inline Styling β CSS written as JavaScript objects
CSS Modules β Locally scoped CSS styles
Styled Components β Component-level styles written in JavaScript
Sass Stylesheets β Sass-based styles compiled into CSS
Post-Processed Stylesheets β CSS generated using post-processing tools
In this section, we will focus on three important styling methods:
CSS Stylesheets
Inline Styling
CSS Modules
1. CSS Stylesheets
Β
CSS stylesheets are the most common and time-tested way to style React components. You create a CSS file for a component and apply styles using the className attribute.
Step 1: Add Styles in CSS File
Open ExpenseEntryItem.css and add the following styles:
Β
div.itemStyle { Β color: brown; Β font-size: 14px; }
Step 2: Apply the Class in the Component
Open ExpenseEntryItem.js and add className to the main container:
Β
import React from 'react'; import './ExpenseEntryItem.css'; class ExpenseEntryItem extends React.Component { Β render() { Β Β Β return ( Β Β Β Β
Run the Application
Β
npm start
Open the browser at http://localhost:3000.
Drawbacks of CSS Stylesheets
Class name conflicts in large projects
CSS imports depend on tools like Webpack
2. Inline Styling
Β
Inline styling is one of the safest ways to style React components. Styles are defined as JavaScript objects and applied using the style attribute.
Define Styles as an Object
Β
itemStyle = { Β color: 'brown', Β fontSize: '14px' };
CSS properties are written in camelCase (e.g., fontSize instead of font-size).
Apply Inline Styles
Β
render() { Β return ( Β Β Β
Inline Styles Directly in JSX
Β
Limitations of Inline Styling
No support for :hover, :focus, or media queries
Not suitable for large or complex styles
3. CSS Modules
Β
CSS Modules provide a safe and scalable way to style components. Styles are locally scoped, preventing class name conflicts.
Step 1: Create a CSS Module File
Create ExpenseEntryItem.module.css in src/components:
Β
.itemStyle { Β color: brown; Β font-size: 14px; }
Files ending with .module.css are automatically processed as CSS Modules.
Step 2: Import the Module
Β
import styles from './ExpenseEntryItem.module.css';
Step 3: Use the Scoped Class
Β
Final Component Using CSS Modules
Β
import React from 'react'; import styles from './ExpenseEntryItem.module.css'; class ExpenseEntryItem extends React.Component { Β render() { Β Β Β return ( Β Β Β Β
Run the application:
Β
npm start