React Tutorials
React ES6
React Hooks
There are many ways to style React with CSS, this tutorial will take a closer look at three common ways:
To make a style object with an inline style attribute, the value must be a JavaScript object:
Insert an object with the styling information:
const Header = () => {
return (
<>
<h1 style={{color: "red"}}>Hello Style!</h1>
<p>Add a little style!</p>
</>
);
}
Note: In JSX, JavaScript expressions are enclosed in curved parentheses, and since JavaScript objects use folded parentheses, the style in the example above is written within two sets of curved parentheses {{}}
.
Since the CSS inline is written in a JavaScript object, structures with link separators, such as background-color
, should be written with the camel case syntax:
Use backgroundColor
instead of background-color
:
const Header = () => {
return (
<>
<h1 style={{backgroundColor: "lightblue"}}>Hello Style!</h1>
<p>Add a little style!</p>
</>
);
}
You can also create an item with style information, and refer to it in the style attribute:
Create a style object named myStyle
:
const Header = () => {
const myStyle = {
color: "white",
backgroundColor: "DodgerBlue",
padding: "10px",
fontFamily: "Sans-Serif"
};
return (
<>
<h1 style={myStyle}>Hello Style!</h1>
<p>Add a little style!</p>
</>
);
}
You can write your CSS style in a separate file, just save the file with the .css
file extension, and import it into your application.
Create a new file called "App.css" and insert some CSS code in it:
body {
background-color: #282c34;
color: white;
padding: 40px;
font-family: Sans-Serif;
text-align: center;
}
Note: You can file whatever you like, just remember the appropriate file extension.
Import style sheet into your app:
import React from 'react';
import ReactDOM from 'react-dom';
import './App.css';
const Header = () => {
return (
<>
<h1>Hello Style!</h1>
<p>Add a little style!.</p>
</>
);
}
ReactDOM.render(<Header />, document.getElementById('root'));
Another way to add styles to your app is to use CSS modules.
CSS modules are suitable for sections placed in different files.
CSS within the module is only available in the imported section, and you do not have to worry about word conflicts.
Create a CSS module with the .module.css
extension, for example: my-style.module.css
.
Create a new file called "my-style.module.css" and insert some CSS code in it:
.bigblue {
color: DodgerBlue;
padding: 40px;
font-family: Sans-Serif;
text-align: center;
}
Import style sheet into your section:
import styles from './my-style.module.css';
const Car = () => {
return <h1 className={styles.bigblue}>Hello Car!</h1>;
}
export default Car;
Import a component to your application:
import ReactDOM from 'react-dom';
import Car from './Car.js';
ReactDOM.render(<Car />, document.getElementById('root'));