It might be helpful to walk through the code for the TextBoxList
component:
The first time through we have a state variable called count
that is set to 1
.
var TextBoxList = React.createClass({
getInitialState: function() {
return {count: 1};
},
The add
function will increment the value of count
by one each time it is called.
add: function() {
this.setState({count: this.state.count + 1});
},
The render
function starts by creating an empty array called items
.
render: function() {
var items = [];
then loops count
times. So, the first render, the loop runs only once, since count
is 1
.
for (var i = 0; i < this.state.count; i++) {
adding an input
element to the items
array each iteration.
items.push(
<li key={i}>
<input type="text" placeholder="change me!" />
</li>
);
}
and finally rendering our items
array along with an add
button
return (
<ul>
{items}
<input type="button" value="Add an item" onClick={this.add} />
</ul>
);
}
});
When the add
button is clicked.The process starts over and count
is set to 2
meaning that we will now add two input
elements to our items
array.
React compares this new state (2 input
elements) to the previous state (1 input
element) and notices that only 1 input
has changed. So, it adds only 1 input
to the actual DOM, preserving the previous input
since it hasn’t changed.
Each time we click the add
button, React notices that there is only 1 new input
so it leaves the others and only adds the new one.
Hope that helps.