Shh
Shh

Reputation: 309

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?

Upvotes: 6

Views: 21437

Answers (4)

Faiyaz Alam
Faiyaz Alam

Reputation: 1

handleReset = () => { setState(({ name: '', email: '', })) }

Upvotes: 0

Veda dhanraj Verma
Veda dhanraj Verma

Reputation: 1

Note:- use this one in functional component.

const handleReset = (e) => {
    e.preventDefault();
    setState(prevState => ({
        ...prevState,
        name: '',
        email: '',
        password: ''
    }))
}

Upvotes: 0

Dulya Perera
Dulya Perera

Reputation: 157

You can do this simply like this.

Before the render() add below part. This is a function to reset the fields.

      reset = () => {
      this.setState({ firstname: ''})
      this.setState({ lastname: ''})
  }

And this where the function is called. (In Button onPress.)

<Button 
    title='reset'
    style={styles.button}
    onPress={this.reset}
    >
</Button>

Upvotes: 0

Ben Ammann
Ben Ammann

Reputation: 712

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.

Upvotes: 9

Related Questions