In this lesson, we are going to discuss how to add CSS styles to our React app. Take a look inside the src
directory, and you'll notice the following structure:
1.
2├── README.md
3├── index.html
4├── package-lock.json
5├── package.json
6├── public
7│ └── vite.svg
8├── src
9│ ├── App.css <===
10│ ├── App.jsx <===
11│ ├── assets
12│ ├── index.css
13│ └── main.jsx
14└── vite.config.js
External CSS files
By default, the project is organized in a way so that each component has a corresponding CSS file. This arrangement ensures that each component imports only the CSS styles it needs.
For example, take a look at the App.css
and App.jsx
. This is where you define the styles specifically for the App
component.
App.css
1#root {
2 max-width: 1280px;
3 margin: 0 auto;
4 padding: 2rem;
5 text-align: center;
6}
7
8.logo {
9 height: 6em;
10 padding: 1.5em;
11 will-change: filter;
12 transition: filter 300ms;
13}
14. . .
Inside the the corresponding App.jsx
file, we need to import this App.css
file at the top to apply these styles to our component.
App.jsx
1import "./App.css";
When assigning these CSS styles to JSX elements, you must use the className
attribute, which works exactly the same as the class
attribute in HTML.
The reason we need to use className
instead of class
is to avoid conflict with the built-in class
keyword in JavaScript.
1import { useState } from "react";
2import reactLogo from "./assets/react.svg";
3import viteLogo from "/vite.svg";
4import "./App.css";
5
6function App() {
7 const [count, setCount] = useState(0);
8
9 return (
10 <>
11 <div>
12 <a href="https://vitejs.dev" target="_blank">
13 <img src={viteLogo} className="logo" alt="Vite logo" />
14 </a>
15 <a href="https://react.dev" target="_blank">
16 <img src={reactLogo} className="logo react" alt="React logo" />
17 </a>
18 </div>
19 <h1>Vite + React</h1>
20 <div className="card">
21 <button onClick={() => setCount((count) => count + 1)}>
22 count is {count}
23 </button>
24 <p>
25 Edit <code>src/App.jsx</code> and save to test HMR
26 </p>
27 </div>
28 <p className="read-the-docs">
29 Click on the Vite and React logos to learn more
30 </p>
31 </>
32 );
33}
34
35export default App;
Inline styles
Alternatively, you can apply styles directly to elements using inline styles. Inline styles are useful for adding dynamic styles or quick adjustments without creating a new CSS class.
1<button style={{ backgroundColor: "lightblue", color: "darkblue" }}>
2 Click me
3</button>
Notice that they’re applied as an object of CSS properties in camelCase format, meaning background-color
becomes backgroundColor
.
Inline styles can be especially useful when styling according to a component’s state, which is a concept in React we are going to introduce later. For now, you can think of it as a variable.
When you aim to create a system where the UI changes according to this state variable, it is usually more convenient to use inline styles, as it provides a quick way to modify styles without creating additional CSS classes. For example:
1import { useState } from "react";
2
3function InlineStyledButton() {
4 const [isActive, setIsActive] = useState(false);
5
6 return (
7 <button
8 style={{
9 backgroundColor: isActive ? "green" : "gray",
10 }}
11 onClick={() => setIsActive(!isActive)}>
12 {isActive ? "Active" : "Inactive"}
13 </button>
14 );
15}
16
17export default InlineStyledButton;
CSS-in-JS
CSS-in-JS is a new styling technique that allows you to write CSS code directly inside JavaScript. It works similarly to external CSS files, where each component has their own styles, except with CSS-in-JS, you no longer need to jump between multiple files.
And similar to the inline style method, since the code lives inside the JavaScript file, it works seamlessly with other concepts in React, including states.
Common CSS-in-JS libraries include Styled-Components, Emotion, JSS, and more. You can check out the linked websites for details on how to use these libraries. We are going to skip them in this lesson, as this is not the focus of our course.
CSS frameworks
Lastly, you can use a CSS framework instead. TailwindCSS is a popular utility-first CSS framework which we have discussed in the linked article. Open the terminal and run the following command to install the necessary packages.
1npm install -D tailwindcss postcss autoprefixer
And then initialize TailwindCSS:
1npx tailwindcss init -p
A tailwind.config.js
file should be generated. Open it, and make sure all of your JSX files are included under the content
option:
1/** @type {import('tailwindcss').Config} */
2export default {
3 content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"],
4 theme: {
5 extend: {},
6 },
7 plugins: [],
8};
Finally, add the following code to your index.css
file:
1@tailwind base;
2@tailwind components;
3@tailwind utilities;
Also make sure index.css
is imported into main.jsx
.
1import React from "react";
2import ReactDOM from "react-dom/client";
3import App from "./App.jsx";
4import "./index.css";
5
6ReactDOM.createRoot(document.getElementById("root")).render(
7 <React.StrictMode>
8 <App />
9 </React.StrictMode>
10);
And now, you can start using TailwindCSS in your React project.
1export default function App() {
2 return <h1 className="text-3xl font-bold underline">Hello world!</h1>;
3}