About Lesson
Styling React Using CSS:
There are many ways to style React with CSS, this tutorial will take a closer look at three common ways:
- Inline styling
- CSS stylesheets
- CSS Modules
Inline Styling:
Inline styles are applied directly to elements using the style attribute. The style object follows JavaScript syntax (camelCase properties).
Example:
import React from "react";
JavaScript
function InlineStyle() {
return <h2 style={{ color: "blue",fontSize: "24px",textAlign: "center" }}>This is an inline styled heading</h2>;
}
export default InlineStyle;
CSS Stylesheets (Global CSS):
CSS Stylesheets (Global CSS):
You can write regular CSS styles in a separate .css file and import it into your React component.
App.css (Stylesheet):
CSS
.heading {
color: green;
font-size: 24px;
text-align: center;
}
App.js:
JavaScript
import React from "react";
import "./App.css"; // Importing CSS fill
function StylesheetExample() {
return <h2 className="heading">This is a styled heading using CSS file</h2>;
}
export default StylesheetExample;
CSS Modules (Scoped Styling):
CSS Modules allow component-specific styles to avoid conflicts. The styles are locally scoped to the component.
Button.module.css:
CSS
.button {
background-color: purple;
color: white;
padding: 10px 20px;
border: none;
cursor: pointer;
}
.button:hover {
background-color: darkviolet;
}
Button.js:
JavaScript
import React from "react";
import styles from "./Button.module.css"; // Importing CSS Module
function Button() {
return <button className={styles.button}>Click Me</button>;
}
export default Button;