I am currently trying to clear the input field every time I try to submit the form but the content won’t disappear
export default function MainContent() {
const [note, setNotes] = React.useState('')
const { addToContainer } = React.useContext(notesContext)
const useRef = React.useRef(null)
function change(e) {
const { value, name, id } = e.target
setNotes(prevNote => {
return {
...prevNote,
[name] : value
}
})
}
function handleSubmit(e) {
e.preventDefault()
addToContainer(note)
}
return (<div><div className="main">Here are your notes!</div>
<form onSubmit={(e) => handleSubmit(e)}><textarea name="notes" onChange={(e) => change(e)} id="notes" value={note.notes} />
<button>Submit here</button>
</form>
</div>)
}
I have tried to setNotes('')
when submitting it but that does nothing.
3
Answers
You could extend the
handleSubmit()
function to reset theuseState()
:Small demo based on your code:
There seems to be an inconsistency on whether
note
is a string:Or an object:
The markup expects an object (with a
notes
property):This could very well cause confusion in the rendering of the form element because sometimes the value is
undefined
(whether initially or after setting state back to''
, in both casesnote.notes
isundefined
), which could be switching this back and forth from a controlled to uncontrolled form element.At the very least, this should be consistent. If the intent is to use an object, initialize it as such:
And reset it by resetting that object:
Example:
Alternatively, if you would rather just use a simple string instead of an object:
The code used to update the state in the
change
function implies that the intent is to add other fields to the object, though the name of the object doesn’t imply that at all. But the point is to pick one or the other.I think you should not give an object to the value of
<textarea />
,I mean that the value must be a string type.
You said that you tried
setNotes('')
, which didn’t work at all, (Have you changed the value fromnote.notes
tonote
), I think the following code must be like that: