React CSS Styling
There are many ways to style React with CSS, however this lesson will focus on three typical methods:
- Inline styling
- CSS stylesheets
- CSS Modules
Inline Styling
Insert an object with the styling information.
Example:
const Header = () => {
return (
<>
Hello Style!
Add a little style!
>
);
}
Note: In JSX, JavaScript expressions are placed inside curly braces. Because JavaScript objects also utilize curly braces, the style in the example above is written inside two sets of curly braces {{}}.
camelCased Property Names
Because inline CSS is written in a JavaScript object, attributes with hyphen separators, such as background-color, must be written using camel case syntax:
Example
Use backgroundColor rather than background-color.
const Header = () => {
return (
<>
Hello Style!
Add a little style!
>
);
}
JavaScript Object
You can also build an object with styling information and use it in the style attribute:
Example
Create a style object called myStyle:
const Header = () => {
const myStyle = {
color: "white",
backgroundColor: "DodgerBlue",
padding: "10px",
fontFamily: "Sans-Serif"
};
return (
<>
Hello Style!
Add a little style!
>
);
}
CSS Stylesheet
You can write your CSS styling in a separate file; simply save it with the.css extension and import it into your application.
App.css:
Create a new file called “App.css” and add some CSS code to it:
body {
background-color: #282c34;
color: white;
padding: 40px;
font-family: Sans-Serif;
text-align: center;
}
Note: You can call the file whatever you want; just remember the correct file extension.
Import the css into your application.
index.js:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './App.css';
const Header = () => {
return (
<>
Hello Style!
Add a little style!.
>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render( );
CSS Modules
CSS Modules are another option to add style to your program.
CSS Modules are useful for components that are kept in different files.
CSS inside a module is only available to the component that imported it, thus there are no name conflicts to worry about.
Create a CSS module using the .module.css extension, like my-style.module.css.
Create a new file called “my-style.module.css” and insert some CSS code into it.
my-style.module.css:
.bigblue {
color: DodgerBlue;
padding: 40px;
font-family: Sans-Serif;
text-align: center;
}
Import the stylesheet in your component:
Car.js:
import styles from './my-style.module.css';
const Car = () => {
return Hello Car!
;
}
export default Car;
Import the component into your app:
index.js:
import ReactDOM from 'react-dom/client';
import Car from './Car.js';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render( );