Reputation: 79
I have the following code for adding a comment into a table
const [newComment, setNewComment] = useState('')
<textarea onChange={e => setNewComment(e.target.value)} placeholder='Add a comment'/>
<button onClick={() => AddComment(newComment)}>Add</button>
After I click on the button to add a comment, I would like the textarea value to clear/reset to the original placeholder 'Add a comment'. Currently after I press the button, the comment gets added however the textarea retains the 'newComment" value meaning I then have to manually clear it before I insert a new comment which is not very convenient - any suggestions?
Upvotes: 0
Views: 784
Reputation: 345
I think you want to make the textarea what React calls a "controlled component" by giving it a value
attribute that reflects the newComment
state:
const [newComment, setNewComment] = useState("");
return (
<div>
<textarea
onChange={e => setNewComment(e.target.value)}
placeholder="Add a comment"
value={newComment}
/>
<button
onClick={() => {
AddComment(newComment)
setNewComment("");
}}
>
Add
</button>
</div>
);
Upvotes: 1
Reputation: 1175
It should work. After you press a button you set the value to empty string
const [newComment, setNewComment] = useState('')
<input value={newComment} onChange={e => setNewComment(e.target.value)} placeholder='Add a comment'/>
<button onClick={() => {
AddComment(newComment)
setNewComment('')
}}>Add</button>
Upvotes: 1