1

I am having some difficulty getting my input form to reset on submit. I would like for the input field to reset to a blank value when the form is submitted successfully, but for the time being I am also fine with it just resetting onSubmit in general, neither of which I have been able to figure out so far. Specifically, what I tried was:

 class SubscribeForm extends React.Component {
  constructor(props, ...args) {
    super(props, ...args)
    this.state = {
      status: null,
      msg: null,
    };
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {
  event.preventDefault();
  this.setState({ value: '' });
}

With the form layout:

<form onSubmit={this.handleSubmit} action={action} method="post" id="alert-form" noValidate>

                <input
                  ref={node => (this.input = node)}
                  type="email"
                  defaultValue=""
                  name="EMAIL"
                  required={true}
                  placeholder={messages.inputPlaceholder}
                />
                <button
                  disabled={this.state.status === "sending" || this.state.status === "success"}
                  onClick={this.onSubmit}
                  type="submit"
                  className="btn-group"
                  id="AlertButton"
                >
                  <p>Sign Up</p>
                </button>
                  </form>

However, calling {this.handleSumbit} in the onSubmit prop of the Form does not appear to have any result when the button is actually clicked. Is there anything obvious i'm missing here or is it a more complex problem?

Provided below is the full relevant code snippet:

class SubscribeForm extends React.Component {
  constructor(props, ...args) {
    super(props, ...args)
    this.state = {
      status: null,
      msg: null,
    };
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {
  event.preventDefault();
  this.setState({ value: '' });
}

  onSubmit = e => {
    e.preventDefault()
    if (!this.input.value || this.input.value.length < 5 || this.input.value.indexOf("@") === -1) {
      this.setState({
        status: "error"
      })
      return
    }
    const url = getAjaxUrl(this.props.action) + `&EMAIL=${encodeURIComponent(this.input.value)}`;
    this.setState(
      {
        status: "sending",
        msg: null
      }, () => jsonp(url, {
        param: "c"
      }, (err, data) => {
        if (err) {
          this.setState({
            status: 'error',
            msg: err
          })
        } else if (data.result !== 'success') {
          this.setState({
            status: 'error',
            msg: data.msg,
          })

        } else {
          this.input.defaultValue = "";
          this.setState({
            status: 'success',
            msg: data.msg,
            inputPlaceholder: "E-mail"
          })
        }
      })
    )
  }
  render() {
    const { action, messages, className, style, styles } = this.props
    const { status, msg } = this.state
    return (
      <div className={className} style={style}>
        <form onSubmit={this.handleSubmit} action={action} method="post" id="alert-form" noValidate>

            <input
              ref={node => (this.input = node)}
              type="email"
              defaultValue=""
              name="EMAIL"
              required={true}
              placeholder={messages.inputPlaceholder}
            />
            <button
              disabled={this.state.status === "sending" || this.state.status === "success"}
              onClick={this.onSubmit}
              type="submit"
              className="btn-group"
              id="AlertButton"
            >
              <p>Sign Up</p>
            </button>
              </form>

      </div>
    )
  }
}
user8891334
  • 171
  • 1
  • 4
  • 10

2 Answers2

1

Try this

handleSubmit(event) {
    event.preventDefault();
    this.input.value = '';
    this.setState({ value: '' });
}

https://codepen.io/va0000ll/pen/zRXNwY

mohamedvall
  • 144
  • 2
  • 4
0

You could make SubscribeForm a controlled component. https://reactjs.org/docs/forms.html

This means adding an onChange that updates this.state.value and setting the value of the input field to this.state.value.

If you do this your setState({value: ''}) would cause a render of the form with the value set back to empty string.

It creates a two way binding. When the input field is updated, so is the component state. When the component state is updated, so is the input field.

Since you are using onSubmit, you can get the input field from the event. Something like event.target.elements.EMAIL.value = ''. I would prefer this over using the ref that you have there.

jens
  • 2,075
  • 10
  • 15