How to update input value using ref in ReactJS
I have one input which i want to update using ref only(not using setState). constructor(props) { super(props);
this.Increase = this.Increase.bind(this)
this.textInput = React.createRef();
this.state = {
inputVal: -1
};
}
<div>
<input type="number" ref={textInput} placeholder="count"/>
<span onClick={this.Increase}>Increase
</span>
</div>
and i have one function where i want to use to increase input value
Increase(event){
//access ref here and update input value using ref
}
Any help will be appreciated.
Thanks
Solution 1:
It's just like changing a mere normal field value. You could just do :
Increase(event) {
event.preventDefault();
this.textInput.current.value += 1;
}
Solution 2:
The first step to fix this problem is to pass the ref properly:
<div>
<input type="number" ref={this.textInput} placeholder="count"/>
<span onClick={this.Increase}>Increase</span>
</div>
then you should add this Increase
function:
Increase(event) {
event.preventDefault();
this.textInput.current.value = "2" //everything you want;
}