Styling
Style elements from a component with the style prop.
Your React code is compiled and run by React itself, inside your browser tab. Nothing to install.
The style prop
In JSX, style takes a JavaScript object, so there are two pairs of curly brackets: the outer pair switches to JavaScript and the inner pair is the object.
Property names are in camel case: fontSize, not font-size. Values are strings, such as "24px".
export default function App() {
return (
<h1 style={{ color: "crimson", fontSize: "32px" }}>Fresh today</h1>
);
}Your turn: style a heading
Two properties in one object.
Practice task
Show an h1 that says Sale, in green, with a font size of 40px.
Your answer is run and checked in the lesson. Create a free account to try it.
Style that follows state
Because a style is an ordinary object, its values can come from state.
Here the box changes colour each time the button is clicked.
import { useState } from "react";
export default function App() {
const [warm, setWarm] = useState(false);
return (
<div>
<p style={{ backgroundColor: warm ? "gold" : "lightblue", padding: "12px" }}>The oven is {warm ? "warm" : "cold"}</p>
<button onClick={() => setWarm(!warm)}>Change</button>
</div>
);
}Your turn: a colour that changes
Combine state with a style.
Practice task
Show a paragraph that says Status with red text, and a button that says Fix. After the button is clicked, the paragraph's text must be green.
Your answer is run and checked in the lesson. Create a free account to try it.