React.js, timeout - how to hide a div after a few seconds

Viewed 4407

I am making a form using react.js. I am attempting to make a div appear and then disappear after the form has been submitted. How can I correctly do this?

My code currently just take me to a blank page when the form has been submitted.

Updated on request

  constructor(props) {
    super(props)
    this.state = {
      messageConfirm: ''
    }

    this.handleInput1 = this.handleInput1.bind(this);
    this.handleInput2 = this.handleInput2.bind(this);
    this.handleInput3 = this.handleInput3.bind(this);
    this.sendEmail = this.sendEmail.bind(this)
    this.submitForm = this.submitForm.bind(this)
  }

  resetForm() {
   //reset form
  }

  validateForm() {
    //validate form method
  }

  sendEmail(e) {
  //send email method
  }

  confirmEmailMessage(){
    this.setState({messageConfirm: "Thanks for your message"})
  }

  setTimeOut(){
    this.setState({messageConfirm: ""}, 5000)
  }
  
  
  submitForm(e) {
    e.preventDefault();
    const isValid = this.validateForm();
    if (isValid) {
      // this.sendEmail(e)
      this.confirmEmailMessage()
      this.setTimeOut()
      e.target.reset()
      this.resetForm()
    }
  }

  render() {
    return (
      <div className="container">
        <div className="contact-form container-fluid d-flex justify-content-center bd-highlight" id="contact-form">
          <form onSubmit={this.submitForm} data-testid="form">
            //form code
          </form>
        </div>
        <div>
        </div>
      </div>
    )
  }
}
1 Answers

React's this.setState's second argument is a callback function, not a static value. You probably meant to call setTimeout with a callback to update state. I also suggest changing the name of your function to something more meaningful, like resetMessage so it isn't as ambiguous. Then for completionist's sake you should save the timer ref and clear it when the component unmounts so you don't try to set state of an unmounted component.

constructor(props) {
  super(props)
  this.state = {
    messageConfirm: '',
  };
  this.timerId = null;
}

resetMessage() {
  this.timerId = setTimeout(() => {
    this.setState({ messageConfirm: "" });
     this.timerId = null;
  }, 5000);
}

submitForm(e) {
  e.preventDefault();
  const isValid = this.validateForm();

  if (isValid) {
    this.confirmEmailMessage();
    this.resetMessage();
    e.target.reset();
    this.resetForm();
  }
}

...

componentWillUnmount() {
  cleatTimeout(this.timerId);
}
Related