Lesson 13 of 3043%
(Progress persistence is disabled until Phase 9)
React
Beginner
Default Values
Handling missing props with default values.
What happens if a parent forgets to pass a prop? It will be undefined.
You can use standard JavaScript default parameters to handle this safely!
function Avatar({ url = "/default-avatar.png", size = 50 }) {
return <img src={url} width={size} height={size} alt="Avatar" />;
}
function App() {
return (
<div>
{/* Uses the defaults! */}
<Avatar />
{/* Overrides the defaults! */}
<Avatar url="/me.jpg" size={100} />
</div>
);
}
Try It Yourself