There are several methods to style React components with CSS. Here are three methods you can use.
- Inline Styling
- CSS Stylesheets
- CSS Modules
Inline Styling
To apply styles directly to an element using the style
attribute, the value should be a JavaScript object:
Embed an object containing the styling details:
const Title = () => {
return (
<>
<h1 style={{ color: "green" }}>Hello Style!</h1>
<p>Enhance your style!</p>
</>
);
};
Note: In JSX, JavaScript expressions are enclosed in curly braces, and since JavaScript objects also use curly braces, the styling above uses double curly braces {{}}
.
camelCased Property Names
When using inline CSS in a JavaScript object, properties with hyphen separators like background-color
should be written in camelCase:
Use backgroundColor
instead of background-color
:
const Title = () => {
return (
<>
<h1 style={{ backgroundColor: "lightgreen" }}>Hello Style!</h1>
<p>Enhance your style!</p>
</>
);
};
JavaScript Object
You can also define an object containing styling details and reference it in the style
attribute:
Create a style object named styleObject
:
const Title = () => {
const styleObject = {
color: "black",
backgroundColor: "LightSkyBlue",
padding: "15px",
fontFamily: "Arial"
};
return (
<>
<h1 style={styleObject}>Hello Style!</h1>
<p>Enhance your style!</p>
</>
);
};
CSS Stylesheet
CSS styles can be written in a separate file. Save the file with a .css
extension and import it into your application.
App.css:
Create a new file named App.css
and add some CSS code:
body {
background-color: #333;
color: white;
padding: 20px;
font-family: Arial, sans-serif;
text-align: left;
}
Note: You can name the file as you prefer, just ensure it has the correct file extension.
Import the Stylesheet in Your Application:
import React from "react";
import ReactDOM from "react-dom/client";
import "./App.css";
const Title = () => {
return (
<>
<h1>Hello Style!</h1>
<p>Enhance your style!</p>
</>
);
};
const rootElement = ReactDOM.createRoot(document.getElementById('root'));
rootElement.render(<Title />);
CSS Modules
Another way to add styles to your application is using CSS Modules. CSS Modules are convenient for components that are placed in separate files. The CSS in a module is scoped to that component, avoiding conflicts.
Create the CSS module with the .module.css
extension, for example: custom-style.module.css
.
custom-style.module.css:
.highlighted {
color: MediumSeaGreen;
padding: 50px;
font-family: Arial, sans-serif;
text-align: center;
}
Import the Stylesheet in Your Component:
import styles from "./custom-style.module.css";
const Vehicle = () => {
return <h1 className={styles.highlighted}>Hello Vehicle!</h1>;
};
export default Vehicle;
Import the Component in Your Application:
import ReactDOM from "react-dom/client";
import Vehicle from "./Vehicle.js";
const rootElement = ReactDOM.createRoot(document.getElementById('root'));
rootElement.render(<Vehicle />);