Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React JS How to reset a form

How do I reset the values in a form in React JS onClick?

class AddFriendForm extends Component {
  constructor(props) {
   super(props)
   this.state = {
     firstname: '',
     lastname: '',
   }
 }

 render() {
    const { addFriend } = this.props

   const setFirstName = add => this.setState({ firstname: add.target.value })
   const setLastName = add => this.setState({ lastname: add.target.value })

return (
  <div>
    <div>
      <Label label="First Name" />
      <Field onChange={setFirstName} />

      <Label label="Last Name" />
      <Field onChange={setLastName} />

      <SecondaryButton
        name="Search"
        onClick={() => addFriend(this.state)}
      />

   <SecondaryButton
      name="Reset"
      onClick={() => ???}
      />
    </div>
  </div>
)
 }
}

When the user presses the Reset button, I want an onClick event that resets all the fields in the form to blank. Is there a single line of code to do this?

like image 982
Shh Avatar asked Jan 29 '23 00:01

Shh


1 Answers

First, create a function called resetForm

resetForm = () => {
   this.setState({
       ...this.state,
       firstname: '',
       lastname: ''
   })
}

Then trigger the function when reset button is clicked

onClick={this.resetForm}

Cheers mate

EDIT:

You have to assign the values to "Field" using value={this.state.firstname}

<Field value={this.state.firstname} onChange={...

Small tip: dont define your functions in your jsx code.

like image 88
Ben Ammann Avatar answered Feb 05 '23 15:02

Ben Ammann