in React app, I have a situation, where I need to tie only one button out of two to form submission task. Right now, both buttons submit my data. Here is some code:
<div>
<h2>create a new anecdote</h2>
<form onSubmit={handleSubmit}>
<div>
content
<input {...content} />
</div>
<div>
author
<input {...author} />
</div>
<div>
url for more info
<input {...info} />
</div>
<button onClick={()=> {
props.setNotification(content.value);
setTimeout(() => {
props.setNotification('')
}, 5000)
}}>
create
</button>
<button onClick={handleReset}>Reset</button>
</form>
</div>
I have tried to put the "Reset" button outside of form. But then, my buttons would sit on the same line, being one on top of the other. I need the Reset button to be inside the form, so they naturally sit next to each other.
More code:
const CreateNew = (props) => {
const content = useField('content')
const author = useField('author')
const info = useField('info')
const navigate = useNavigate()
const handleSubmit = (e) => {
if (content.value === '' || author.value === '' || info.value === '') {
return
}
e.preventDefault()
props.addNew({
content: content.value,
author: author.value,
info: info.value,
votes: 0
})
navigate('/')
}
const handleReset = (e) => {
if (content.value === '' || author.value === '' || info.value === '') {
return
}
e.preventDefault()
props.addNew({
content: content.onReset(''),
author: author.onReset(''),
info: info.onReset(''),
votes: 0
})
}
With the above code, I have created a bug, where I can clear inputs boxes, but then happens I accidently submit an empty data with the same one click on Rest.
CodePudding user response:
Set button type explicitely: <button type="button" onClick={handleReset}>Reset</button>
This works because it overrides the default button type which is "submit".
CodePudding user response:
give type="submit" to the button you want to tie to form submission.have a look