Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset form input values in React

I want create a function using with i can reset value in form inputs without submit. I tried create that function in App Component (resetFormFields) and pass it on props to Form Component. It's preety simply when I want to do this onSubmit (e.target.reset()) but I got stuck when I have to do it without submit, on a different element than the form. Can I do that without adding these values to state?

App:

class App extends Component {

state = {
    people: [],
    formMessages: [],
    person: null
};

handleFormSubmit = e => {

    e.preventDefault();

    const form = e.target;
    const name = form.elements["name"].value;
    const username = form.elements["username"].value;

    this.addPerson(name, email);
    form.reset();
};

resetFormFields = () => {
    return;
}

render() {

    return (
        <div className="App">
            <Form formSubmit={this.handleFormSubmit} 
                  reset={this.resetFormFields} />
        </div>
    );
}

Form:

    const Form = props => (
  <form className={classes.Form}
    id="form"
    onSubmit={props.formSubmit}>

    <input autoFocus
        id="name"
        type="text"
        defaultValue=""
        placeholder="Name..."
    />
    <input
        id="email"
        type="text"
        defaultValue=""
        placeholder="Email..."
    />
    <Button
        btnType="Submit"
        form="form"
        type='submit'>
        Submit
    </Button>
    <label onClick={props.reset}>Reset fields</label>
</form> );
like image 504
sosick Avatar asked Sep 04 '25 03:09

sosick


1 Answers

onHandleFormSubmit = (e) =>{  
    e.preventDefault();
    e.target.reset();
}
like image 108
abayomi igwubor Avatar answered Sep 05 '25 19:09

abayomi igwubor