How to Clear Input After Onclick With Reactjs

ReactJS clear input value (can not use submit) after button click

Your input is controlled input. You have value set to be value={this.state.value} and handle change function is:

handleChange(event) {    this.setState({value: event.target.value});  }

so if you want to reset this input, your reset function would simply set that state.value to be an empty string.

reset = () => { 
this.setState({value: ""});
};

If your input would be uncontrolled (so value and onChange would not be provided) you could change it by accessing it through Ref. (see React.createRef).

Clear input text after click event

I am surprised that this even works the first time. With controlled components in react (ones where you are setting the value like you are with your input). you need to update the value whenever the user changes the text (with the onChange() event).

I made a JS fiddle here with your original code and you can see you can't even update the value in the input. In order to get it to update you need to replace the onBlur event with an onChange event like this JS fiddle. Hope that helps!



Related Topics



Leave a reply



Submit