Commit 15db45e6 authored by Pascal Hartig's avatar Pascal Hartig

React: Remove direct DOM manipulation

Turn the `<input>` into a
[Controlled Component](https://facebook.github.io/react/docs/forms.html#controlled-components)
and avoid fiddling with the DOM in an imperative way.
parent 0d2591b1
...@@ -20,7 +20,8 @@ var app = app || {}; ...@@ -20,7 +20,8 @@ var app = app || {};
getInitialState: function () { getInitialState: function () {
return { return {
nowShowing: app.ALL_TODOS, nowShowing: app.ALL_TODOS,
editing: null editing: null,
newTodo: ''
}; };
}, },
...@@ -34,6 +35,10 @@ var app = app || {}; ...@@ -34,6 +35,10 @@ var app = app || {};
router.init('/'); router.init('/');
}, },
handleChange: function (event) {
this.setState({newTodo: event.target.value});
},
handleNewTodoKeyDown: function (event) { handleNewTodoKeyDown: function (event) {
if (event.keyCode !== ENTER_KEY) { if (event.keyCode !== ENTER_KEY) {
return; return;
...@@ -41,11 +46,11 @@ var app = app || {}; ...@@ -41,11 +46,11 @@ var app = app || {};
event.preventDefault(); event.preventDefault();
var val = React.findDOMNode(this.refs.newField).value.trim(); var val = this.state.newTodo.trim();
if (val) { if (val) {
this.props.model.addTodo(val); this.props.model.addTodo(val);
React.findDOMNode(this.refs.newField).value = ''; this.setState({newTodo: ''});
} }
}, },
...@@ -147,10 +152,11 @@ var app = app || {}; ...@@ -147,10 +152,11 @@ var app = app || {};
<header className="header"> <header className="header">
<h1>todos</h1> <h1>todos</h1>
<input <input
ref="newField"
className="new-todo" className="new-todo"
placeholder="What needs to be done?" placeholder="What needs to be done?"
value={this.state.newTodo}
onKeyDown={this.handleNewTodoKeyDown} onKeyDown={this.handleNewTodoKeyDown}
onChange={this.handleChange}
autoFocus={true} autoFocus={true}
/> />
</header> </header>
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment