MiniGunnR
MiniGunnR

Reputation: 5800

Why does the following React code work?

I am trying to update a p element in realtime while I type on an input element. The following React code works perfectly. However, if I remove the value attribute completely from the input element, the code STILL works!

class ControlledInput extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            input: ''
        };
    }
    handleInput = (event) => {
        this.setState({
            input: event.target.value
        });
    }
    render() {
    return (
        <div>
        <input
            value={this.state.input}
            onChange={this.handleInput} />
        <p>Input: {this.state.input}</p>
        </div>
    );
  }
};

So my questions are:

Upvotes: 1

Views: 80

Answers (2)

Rico Kahler
Rico Kahler

Reputation: 19222

the value={this.state.input} assigns the value of the form to the input box from your component. Your code still works because the event handler still fires when you change the text in the textbox and react doesn't re-render your input. The state of the input value is implicitly in the state of the DOM but this state isn't from your component.

If you had TWO inputs that used the same state, then when you type, the second input won't update. This is where you'll see something different from expected because you omitted the value={this.state.input}. If you include that in both input values then your text boxes will mirror each other.

class ControlledInput extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            input: ''
        };
    }
    handleInput = (event) => {
        this.setState({
            input: event.target.value
        });
    }
    render() {
    return (
        <div>
        <input
            onChange={this.handleInput} />
        <p>Input: {this.state.input}</p>



        <input
            onChange={this.handleInput} />
        <p>Input: {this.state.input}</p>
        </div>
    );
}
};

in the code above, one of the input's won't update when both should have the same state :)

Upvotes: 1

Nelson Yeung
Nelson Yeung

Reputation: 3382

What does the value={this.state.input} line do?

This line sets the value attribute from the input using your state variable input, in your case it will initialise it with '' (nothing) at the start (i.e., this is equivalent to <input value="" ...>) If you change your this.state.input to something like

    this.state = {
        input: 'foo'
    };

you should see how the input value changes to foo upon the start of your program.

Why does the program still work without that line?

Because you are already setting it to be empty at the start so it doesn't actually change anything in your program. Your onChange event handler still fires.

Upvotes: 0

Related Questions