Changing the value of input field - React

Burak ULU picture Burak ULU · Jun 15, 2017 · Viewed 12.6k times · Source

I've been trying to change the value of input field after I select the item from SelectField from MaterialUI library but I haven't succeed it yet but as far as I did search on it, everything that I wrote seems like what it is supposed to be.

This is what I use to change the value;

    var element = ReactDOM.findDOMNode(this.refs._deviceId);
    element.setAttribute('value', 'deneme');
    console.log(element);

This is the input field;

              <div className="form-group row">
                <label className="col-md-2 control-label">Device ID</label>
                <div className="col-md-10">
                  <input type="text" className="form-control" id="deviceId" placeholder="Device ID" ref="_deviceId" />
                </div>
              </div>

And I consoled the element variable after I select the item, in order to check everything is okay and it seems there is no problem.

Here is the console log;

enter image description here

As you see, the value is placed successfully but on the screen, nothing happens to input field.

Answer

Karan Hudia picture Karan Hudia · Jun 15, 2017

Your component needs to be re-rendered after you have set the value attribute. React only re-renders a component when it detects a state change. So rather use a state variable-

//Declare the state variable

this.state = {
    inputValue: ''
};

//Use a lifecycle event or your own method to change the value of that state by using the setState method as-

someMethod() {
    this.setState({
        inputValue: 'deneme'
    });  
}

//In HTML use the above state as-
<input type="text" className="form-control" id="deviceId" placeholder="Device ID" ref="_deviceId" value={this.state.inputValue} />

Remember to use setState method to change the state so that component re render can take place.

OR

You can call this.forceUpdate() to forcefully re-render the component.