简体   繁体   中英

How do you submit a form after hiding the submit button in React

I'm trying to submit a form with a form action. However the submit takes quite a long time, so I'm trying to show a loading message while the form is submitting, telling the user to wait on the screen and they'll be redirected afterwards. The problem is, when I show the loading screen, the form submit no longer works. I've narrowed it down due to the fact that the submit button that triggered the event no longer exists, thus it won't submit. Is there a way to show the loading screen and ensure the submit action goes through?

handleSubmit = () => {
  ...
  this.setState({isLoading: true});
  ...
  this.formRef.current.submit();
}

<form ref={this.formRef} action="https://www.google.com" method="post">
  {isLoading ? (
      this.renderLoading()
  ) : (
      <>
        <input type="text">input</input>
        <button type="submit" onClick={this.handleSubmit}>button<button>
      </>
</form>

I have tried the below solution and it works successfully, however, I don't want the button to be shown in the loading screen.

handleSubmit = () => {
  ...
  this.setState({isLoading: true});
  ...
  this.formRef.current.submit();
}

<form ref={this.formRef} action="https://www.google.com" method="post">
  {isLoading ? (
      this.renderLoading()
  ) : (
      <>
        <input type="text">input</input>
      </>
  <button type="submit" onClick={this.handleSubmit}>button<button>
</form>

Is there a way to make this work without showing the button in the loading screen?

Hide the controls rather than killing them:

handleSubmit = () => {
  ...
  this.setState({isLoading: true});
  ...
  this.formRef.current.submit();
}

<form ref={this.formRef} action="https://www.google.com" method="post">
  <>
  { isLoading && this.renderLoading() }
  <input type="text" className={isLoading ? 'hidden' : ''}>input</input>
  <button type="submit" onClick={this.handleSubmit} className={isLoading ? 'hidden' : ''}>button<button>
  </>
</form>

css for hidden class is display: none

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM