Reset/Set state on a button onClick


I have a custom form with at least two different types of Components: One for a textfield, and another for a number, and when I click the "Submit" button (itself just a button, not wrapped in a form) I want to set the state of the fields back to 0/Empty. I’m not really clear here on how to restore these to their defaults. I know that I need to pass setState() at some point since I can’t "zero out" like with traditional Javascript, but I am confused since the click operation would never reference the components. What am I missing here?

import './App.css';
import React from 'react';

class NumberField extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: 0 };
  }

  changeHandler = event => {
    event.persist();

    let value = event.target.value;

    this.setState(prevState => ({
      item: { ...prevState.value, [event.target.value]: value }
    }))
  };

  render() {
    return (
      <div>
        <label for={this.props.label}>{this.props.labelName}</label>
        <button onClick={this.decrement}>-</button>
        <input type="number" 
          name={this.props.label} 
          id={this.props.label} 
          value={this.state.value}
          onChange={this.changeHandler}>
        </input>
        <button onClick={this.increment}>+</button>
      </div>
    );
  }
}

class TextField extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: "" };
  }

  render() {
    return (
      <div>
        <label for={this.props.label}>{this.props.labelName}</label>
        <input type="text" name={this.props.label} id={this.props.label} placeholder={this.props.placeholder}></input>
      </div>
    );
  }
}

function handleSubmit(e) {
  e.preventDefault();
  console.log("Form Submitted");
  // TODO Reset the state on all components so everything goes back to 0/Empty somehow
}

function App() {
  return (
    <div className="App">
      <div className="AppForm">
        <TextField labelName="Ferry Name" label="ferry_name" placeholder="Enter the ferry name" />

        <div>
          <NumberField labelName="Number of seats" label="seats" />
        </div>
      <div className="formSubmit">
        <button onClick={handleSubmit}>Book Ferry</button>
      </div>
      </div>
    </div>
  );
}

export default App;

Source: React – Stack Overflow

November 28, 2021
Category : News
Tags: react-component | reactjs

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.