React · Lesson 11 of 120
Default Values
Sensible defaults.
Not every prop is always passed. You can give a prop a default value, right where you destructure it. Then the component still works when it's missing.
- Props may be missing
- Default values
- Still works
Badge defaults
Badge has a default colour of light blue, and a default text of new. The first badge uses both defaults. The others pass their own. Run it.
App.jsxjsx
function Badge({ text = "New", colour = "#61dafb" }) {
return (
<span style={{ background: colour, padding: "6px 12px", borderRadius: 8, marginRight: 8 }}>
{text}
</span>
);
}
export default function App() {
return (
<p>
<Badge />
<Badge text="Sale" colour="#fca5a5" />
<Badge text="Electric" />
</p>
);
}Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}Summary
Give props default values in the destructuring, so components work without them. Next, the basics quiz.
Key takeaways- text = 'New'
- Optional props
- Still works
Next up: Basics Quiz — test yourself