8

After I submit my form, which contains data fields and a file field, only the data fields are cleared, but the uploaded file field is kept. See image: Here

OnChange Function

    onChange = (e) => {
        if(e.target.name === 'audio') {
            this.setState({
                [e.target.name]: e.target.files[0], loaded: 0,
            }, () => console.log(this.state.audio))

        } else {

            this.setState({
                [e.target.name]: e.target.value
            }, () => console.log(this.state))
        }
    }

Submit Function


      onSubmit = e => {
    e.preventDefault();
    let { title, content, audio} = this.state;
    //const story = { title, content, audio};
    let formDataStory = new FormData();
    formDataStory.append('audio', audio);
    formDataStory.append('title', title);
    formDataStory.append('content', content);
    this.props.addStory(formDataStory);
    this.setState({
      title: "",
      content:"",
      audio: ""
    });
  };

Form

  render() {
    const {title, content, audio} = this.state;
    return (
      <div className="card card-body mt-4 mb-4">
        <h2>Add Story</h2>
        <form onSubmit={this.onSubmit}>

          <div className="form-group">
            <label>Title</label>
            <input
              className="form-control"
              type="text"
              name="title"
              onChange={this.onChange}
              value={title}
            />
             </div>
           <div className="form-group">
            <label>Content</label>
            <input
              className="form-control"
              type="text"
              name="content"
              onChange={this.onChange}
              value={content}
            />
          </div>

           <div className="form-group">
            <label>Audio</label>
            <input
              className="form-control"
              type="file"
              name="audio"
              onChange={this.onChange}
              //value={audio}
            />
          </div>

         <div className="form-group">
            <button type="submit" className="btn btn-primary">
              Submit
            </button>
          </div>
        </form>
      </div>
    );
  }
}

How can I reset the file upload field together with the other data fields after submitting the form?

Many thanks!

3 Answers 3

20

Since the file input is always uncontrolled you'll need to use a dom ref and manually clear the value.

Here's an example functional component that does this:

function ExampleFileInput() {
  const ref = React.useRef();
  function handleClick() {
    ref.current.value = ""
  }
  return (
    <div className="App">
      <input type="file" ref={ref}/><br />
      <button type="button" onClick={handleClick}>Clear file</button>
    </div>
  );
}

To use in a class component, see the docs. You can read about more ways to clear the file input in this question.

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

Comments

2

Docs

  1. Create ref to file input this.inputRef = React.createRef();
  2. add ref to input <input type="file" ref={this.inputRef} />
  3. Inside submit function this.inputRef.current.value = '';

Comments

1

If you use Formik you can do this:

I had the same issue and I managed it creating a ref in the parent component (the one that use Formik) and passing it to the Field using innerRef prop. Then on the onReset I used the ref to clear the real input value.

const UserForm = props => {
    const logoRef = useRef();

    const handleReset = (values, formikBag) => {
        logoRef.current.value = null; //THIS RESETS THE FILE FIELD
    }

    const handleSubmit = (values, formikBag) => {
        //...
        axios({method, url, data})
            .then(response => {
                formikBag.resetForm();
            })
    }
    //...
    return (
        <Formik initialValues={initialValues} onSubmit={handleSubmit} onReset={handleReset}>
            ...
            <Field
                type="file"
                name="logo"
                onChange={({target}) => setFieldValue(props.name, target.files[0])}
                innerRef={logoRef}
            />
        </Formik>
    )
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.