Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing forms in React after submission

I'm trying to clear the form data once creating a form submission with Axios. The message goes through fine and the response is logged to the page, but the data in each text field remains on the page after submission.

I tried adding a resetForm function where I set the form back to it's original blank state, but that isn't working.

import React, { Component } from 'react';
import { Grid, Cell, Textfield, Button } from 'react-mdl';
import './Contact.css';
import axios from "axios";

class Contact extends Component {
    constructor(props){
        super(props);
        this.state = {fullName: "", email: "", message: ""};
    }  

    resetForm = () => {
        this.baseState = this.state
        this.setState(this.baseState)
    }

    handleForm = e => {
        axios.post(
        "https://formcarry.com/s/axiosID", 
        this.state, 
        {headers: {"Accept": "application/json"}}
        )
        .then(function (response) {
            let successMessage = document.querySelector('.success-message');
            successMessage.innerHTML = JSON.stringify(response.data.title);
        })
        .catch(function (error) {
            let successMessage = document.querySelector('.success-message');
            successMessage.innerHTML = JSON.stringify(error);
        });

        e.preventDefault();
    }
    handleFields = e => this.setState({ [e.target.name]: 'e.target.value' });

        render() {
            return (
                    <Grid>
                        <Cell col={6}>
                            <h2>Contact Me</h2>
                            <hr/>
                            <div style={{ width: '100%' }} className="contact-list">
                                <form onSubmit={this.handleForm}>
                                    <Cell col={12}>
                                        <Textfield type="text" id="fullName" name="fullName" className="full-name"
                                        onChange={this.handleFields}
                                        label="Full name"
                                        floatingLabel
                                        style={{width: '200px'}}
                                        />
                                    </Cell>
                                    <Cell col={12}>
                                    {/* Textfield with floating label */}
                                        <Textfield type="email" id="email" name="email" className="email-address"
                                        onChange={this.handleFields}
                                        label="Email address"
                                        floatingLabel
                                        style={{width: '200px'}}
                                        />
                                    </Cell>
                                    <Cell col={12}>
                                        {/* Floating Multiline Textfield */}
                                        <Textfield name="message" id="message" className="text-body"
                                        onChange={this.handleFields}
                                        label="Your message..."
                                        rows={10}
                                        style={{width: '400px'}}
                                        />
                                    </Cell>
                                    <Button raised accent ripple type="submit" onClick={this.resetForm}>Send</Button>
                                    <div className="success-message">
                                        <label></label>
                                    </div>
                                </form>
                            </div>
                        </Cell>
                    </Grid>
            )
        }
    }


export default Contact;

All I really want is for the text fields fullName, email and message to clear once I submit the form but the data remains on the page.

like image 464
JackJack Avatar asked Apr 12 '26 14:04

JackJack


2 Answers

You do not need the resetForm function (get rid of it altogether), just set your state in the handleForm like so:

UPDATE: You also need to add the value prop to each input to make it a controlled input see below:

import React, { Component } from 'react';
import { Grid, Cell, Textfield, Button } from 'react-mdl';
import './Contact.css';
import axios from "axios";

class Contact extends Component {
  constructor(props) {
    super(props);
    this.state = { fullName: "", email: "", message: "" };
  }

  handleForm = e => {
    axios.post(
      "https://formcarry.com/s/axiosID",
      this.state,
      { headers: { "Accept": "application/json" } }
    )
      .then(function (response) {
        let successMessage = document.querySelector('.success-message');
        successMessage.innerHTML = JSON.stringify(response.data.title);
      })
      .catch(function (error) {
        let successMessage = document.querySelector('.success-message');
        successMessage.innerHTML = JSON.stringify(error);
      });

    e.preventDefault();
    this.setState({fullName: '', email: '', message: ''}) // <= here
  }
  handleFields = e => this.setState({ [e.target.name]: e.target.value }); 

  render() {
    return (
      <Grid>
        <Cell col={6}>
          <h2>Contact Me</h2>
          <hr />
          <div style={{ width: '100%' }} className="contact-list">
            <form onSubmit={this.handleForm}>
              <Cell col={12}>
                <Textfield type="text" id="fullName" name="fullName" className="full-name"
                  onChange={this.handleFields}
                  value={this.state.fullName} // <= here
                  label="Full name"
                  floatingLabel
                  style={{ width: '200px' }}
                />
              </Cell>
              <Cell col={12}>
                {/* Textfield with floating label */}
                <Textfield type="email" id="email" name="email" className="email-address"
                  onChange={this.handleFields}
                  value={this.state.email} // <= here
                  label="Email address"
                  floatingLabel
                  style={{ width: '200px' }}
                />
              </Cell>
              <Cell col={12}>
                {/* Floating Multiline Textfield */}
                <Textfield name="message" id="message" className="text-body"
                  onChange={this.handleFields}
                  value={this.state.message} // <= here
                  label="Your message..."
                  rows={10}
                  style={{ width: '400px' }}
                />
              </Cell>
              <Button raised accent ripple type="submit">Send</Button>
              <div className="success-message">
                <label></label>
              </div>
            </form>
          </div>
        </Cell>
      </Grid>
    )
  }
}


export default Contact;

As a side note: look into React refs for grabbing dom elements... read more here: https://reactjs.org/docs/refs-and-the-dom.html

like image 143
SakoBu Avatar answered Apr 19 '26 03:04

SakoBu


You need to clear the state after submission. After calling setState the react render will be called again with empty values that we set, Hope this helps

 .then(function (response) {
        let successMessage = document.querySelector('.success-message');
         // here clear the state,
         this.setState({
           fullName: '',
           email: '',
           message: '',
         });
        successMessage.innerHTML = JSON.stringify(response.data.title);
    })
like image 38
Aashish Karki Avatar answered Apr 19 '26 04:04

Aashish Karki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!