React doesn't have its own styling language. You style components with CSS, like any web page. There are two everyday ways, and this lab shows both.
npm install and npm run dev. A class chosen by a prop
Badge.jsx builds its class name from its level prop:
<span className={`badge badge-${level}`}>{level}</span>With level="high", the class is badge badge-high. styles.css has a rule
for .badge (the shape) and rules for .badge-high and .badge-low (the
colours). So the component decides which class to use, and the CSS file decides
what that class looks like.
Add a third line to App, <p>Learn hooks <Badge level="medium" /></p>, and
run it. The badge has its shape but no colour, because there's no .badge-medium
rule yet. Add one to styles.css:
.badge-medium {
background: #fff4dc;
color: #8a5a00;
}The style prop
App.jsx also styles one paragraph directly:
<p style={{ fontStyle: "italic", marginTop: "2rem" }}>...</p>Two things look different from HTML:
- Double braces. The outer pair means "a JavaScript value". The inner pair is that value: an object.
- camelCase names. CSS's
font-stylebecomesfontStyle, andmargin-topbecomesmarginTop. Values are strings, so they go in quotes.
Inline styles are handy for a value you calculate, like a progress bar's width. For everything else, prefer classes: they keep the styling in one place and are easier to change.
Predict: what if you write style the HTML way?
Change the paragraph to style="font-style: italic" and run it. React stops
with an error: The style prop expects a mapping from style properties to
values, not a string. Change it back to the object form.
Your turn
A done style
Write a TaskLine component with props title and done. It shows the title
in a <p>. When done is true, the paragraph also gets the class done, which
draws a line through the text and turns it grey. Show one finished and one
unfinished task in App.
npm install and npm run dev. Hint 1: the idea
There are two pieces. The CSS file needs a rule for a class called done
(which CSS properties draw a line through text and change its colour?). The
component needs a className that is "done" when done is true and empty
otherwise. Which JavaScript operator picks one of two values?
Hint 2: a first step
Start with the CSS: add a .done rule with text-decoration: line-through,
then write a fixed className="done" on the <p> for now. Both tasks are
struck through. That proves the rule works; the last step is to make the class
depend on the done prop.
Show one solution
function TaskLine({ title, done }) {
return <p className={done ? "done" : ""}>{title}</p>;
}<TaskLine title="Learn props" done={true} />
<TaskLine title="Learn state" done={false} />And in styles.css:
.done {
text-decoration: line-through;
color: #6b7785;
}Completion is saved in this browser only. It does not measure mastery.