2

This is a ReactJS Problem.

I can't reset multiple input fields of a form.

There is a form in my app that has multiple input fields, I use an onChange function to grab the user inputs, then update this.state with setState, then I copy all the values from this.state with a spread operator and create a new object storing those copied values. Lastly, I pass the new object into a function for further use (not relevant). My code problem is I can't empty the fields after passing the object into a function. I tried manually resetting the values by clearing the values with this.setState, as well as event.target.reset(), but both don't work.

import React, { Component } from "react";

class AddFishForm extends Component {
  // Controlled state
  state = {
    name: "",
    price: "",
    status: "available",
    desc: "",
    image: ""
  };

  // Step 1: onChange: Update this.state
  updateFishState = event => {
    const { name, value } = event.target;
    this.setState({
      [name]: value
    });
  };

  // Step 2: onSubmit: Create Fish Object
  createFish = event => {
    // prevent refresh
    event.preventDefault();
    // copy values inside this.state and paste into new fish object
    const fish = {
      name: this.state.name,
      price: parseFloat(this.state.price),
      status: this.state.status,
      desc: this.state.desc,
      image: this.state.image
    };
    // pass new fish object into addFish() in App.js
    this.props.addFish(fish);
    // ! reset form (NOT WORKING) !
    event.currentTarget.reset();
  };

  render() {
    return (
      <form className="fish-edit" onSubmit={this.createFish}>
        <input
          name="name"
          value={this.state.name}
          type="text"
          placeholder="name"
          onChange={this.updateFishState}
        />
        <input
          name="price"
          value={this.state.price}
          type="text"
          placeholder="price"
          onChange={this.updateFishState}
        />
        <select
          name="status"
          //   Value equals to whichever option is selected
          value={this.optionsState}
          onChange={this.updateFishState}
        >
          <option value="available">Fresh!</option>
          <option value="unavailable">Sold Out!</option>
        </select>
        <textarea
          name="desc"
          value={this.state.desc}
          type="text"
          placeholder="Enter description..."
          onChange={this.updateFishState}
        />
        <input
          name="image"
          value={this.state.image}
          type="text"
          placeholder="image"
          onChange={this.updateFishState}
        />
        <button type="submit">Add Fish</button>
      </form>
    );
  }
}

export default AddFishForm;

I expect the form to be cleared with "event.currentTarget.reset();", but the inputs lingers event after submitting the form. Help?

3 Answers 3

5

That is not how React works. When you create controlled input in React, it's value is controlled by component's state. All you need to remove is event.currentTarget.reset(); and replace it with a simple setState which resets your form values.

this.setState({
  name: "",
  price: "",
  status: "available",
  desc: "",
  image: ""
});

This will reset the values, and react will re-render empty form.

Hope this helps!

Sign up to request clarification or add additional context in comments.

5 Comments

Perfect, it worked! Thanks. It would be cool if you could elaborate more on what you meant by "When you create controlled input in React, it's valued are controlled by component's state"
Sorry for not being elaborate from the start. Thing is that "controlled" inputs in React are maintaining their own state through onChange, which changes value in state. Native .reset() function, does not alter values in the component's state. Therefore our input just continues to use existing value from the state.
Perfect! Thanks Stanko.
okay but now you lose you state values..how can I reset it but keep my state?
You'll need to create a copy of your state, by doing something like const stateCopy = { ...this.state }; before resetting the form.
1

Since you are managing state via your React Component, the best way to reset state is to create a function that sets the values back to an empty string.

The reason why the form.reset() function won't work is that React limits they types of form events: https://reactjs.org/docs/events.html#form-events (Compare to what the reset function does: How does form.reset() work?).

We only get onChange onInput onInvalid onSubmit

So add something like

reset() {
    this.setState({name: "", price: "", status: "available",desc: "",image: ""})
}

Call this function after you addFish.

Comments

0

use this setState method to change your state and rerender the component

this.setState({
  name: "",
  price: "",
  status: "available",
  desc: "",
  image: ""
})

instead of event.currentTarget.reset();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.