Each time I click enter when typing in the form, the app refreshes.
I am trying to capture the input of the form as a value and set the state as that value.
<form>
<input
value={input}
disabled={!channelId}
onChange={(e) => setInput(e.target.value)}
placeholder="what's on your mind..."
/>
<button
type="submit"
disabled={!channelId}
className="chat__inputButton"
>
Send
</button>
</form>
Here is the code. I have tried to manipulate the code using preventDefault(), but that isn't keeping the app from refreshing.
For reference, I am following along with this tutorial: https://www.youtube.com/watch?v=zc1loX80TX8
I tried using preventDefault(), but that didn't work.
When I remove onChange from the input, I am not able to type in the input form.
CodePudding user response:
You can remove the type submit on button and have a event on form as onSubmit
In onSubmit={handleSubmit}
say... It triggers same function for keyboard events too ....
const handleSubmit = (e) => {
e.preventDefault();
}
CodePudding user response:
Your button element requires an onClick
prop, then pass it a function that will also call the preventDefault
function on the event object , the code example:
...
const submitForm = (e) => {
e.preventDefault();
setInput("") // "Resets" input field
//Your functionality...
}
...
return (
...
<button
onClick={submitForm}
//Remaining attributes...
>
Send
</button>
...