I am trying to use the event.preventDefault()
method but I am continuously receiving error. It says that event
has been deprecated.
I am making a Firebase SignUp form and I want to prevent the form from Submitting.
Here is the complete code.
import React from "react" import styled from "styled-components" import getFirebase from "../../firebase" import useInput from "./useInput" const SignUpForm = () => { const firebaseInstance = getFirebase() const email = useInput("") const password = useInput("") const signUp = async () => { event.preventDefault() try { if (firebaseInstance) { const user = await firebaseInstance .auth() .createUserWithEmailAndPassword(email.value, password.value) console.log("user", user) alert(`Welcome ${email.value}!`) } } catch (error) { console.log("error", error) alert(error.message) } } event.preventDefault() return ( <FormWrapper onSubmit={() => signUp()}> <Title>Sign up</Title> <Input placeholder="Email" {...email} /> <Input placeholder="Password" type="password" {...password} /> <Button type="submit">Sign up</Button> </FormWrapper> ) } export default SignUpForm
And the useInput code:
import { useState } from "react" const useInput = initialValue => { const [value, setValue] = useState(initialValue) const handleChange = event => { setValue(event.target.value) } return { value, onChange: handleChange, } } export default useInput
Advertisement
Answer
What that warning means is that the global variable window.event
is deprecated. You can still access the event associated with an event handler, you just have to go about it the proper way – by using the parameter from the handler callback.
Change
<FormWrapper onSubmit={() => signUp()}>
to
<FormWrapper onSubmit={signUp}>
and then signUp
‘s first parameter will be the event, and you’ll be able to use it and call preventDefault
on it as you’re trying.
const signUp = async (event) => {
But don’t put event.preventDefault()
in your functional component’s main body – that is, it shouldn’t be here:
event.preventDefault() return ( ...
Only put it inside the signUp
handler.