Clear Button
Part of the Fundamentals section of Coddy's React journey — lesson 31 of 42.
Here's the controlled-input superpower: since state owns the text, your code can change the box, not just the user. Reset it from anywhere:
<button onClick={() => setName('')}>Clear</button>Set the state to an empty string and the box empties itself on the next render, because value={name} always displays the state. With an uncontrolled input you'd be reaching into the DOM by hand; with state it's one setter call.
Challenge
MediumFinish the message composer.
- Make the input (
id="message") controlled withmessagestate. - Show the draft in the paragraph (
id="draft"): the textDraft:followed by the message. - The
id="clear"button empties the message.
Try it yourself
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div id="root"></div>
<script type="module" src="main.jsx"></script>
</body>
</html>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
2JSX Expressions
Curly BracesMath in BracesBraces in AttributesCalling Functions in JSXRecap: JSX Expressions5State & Events
What Is State?Click CounterCount in StepsToggle with StateIndependent StateRecap: State & Events8Project: Profile Card
Step 1: Card StructureStep 2: Card with PropsStep 3: Like ButtonStep 4: Follow Toggle