React Todo List Example (Adding a Todo)

In notebook:
Egghead Redux
Created at:
2016-07-09
Updated:
2016-07-09
Tags:
libraries React JavaScript pattern
Implements the view layer. Uses React and ReactDOM

He will render into ​<div id="root"></div>​ 
  const { Component } = React;


let nextTodoId = 0;
class TodoApp extends Component {
  render() {
    return (
      <div>
        <button onClick={() => {
          store.dispatch({
            type: 'ADD_TODO',
            text: 'Test',
            id: nextTodoId++
          });
        } }>
          Add Todo
        </button>
        <ul>
          {this.props.todos.map(todo => 
            <li key={todo.id}>
              {todo.text}
            </li>
          )}
        </ul>
      </div>  
    )
  }
}


const render = () => {
  ReactDOM.render(
    <TodoApp todos={store.getState().todos} />,
    document.getElementById('root');
    )  
};

// call render every time the state changes
store.subscribe(render);
render();

with this he has a button and can add new todos.

takes it further:
  const { Component } = React;


let nextTodoId = 0;
class TodoApp extends Component {
  render() {
    return (
      <div>
        // ++++
        // ref is part of React, it's a functions
        <input ref={node = {
          this.input = node;
        }} />
        <button onClick={() => {
          store.dispatch({
            type: 'ADD_TODO',
            // ++-- use the input text
            text: this.input.value,
            id: nextTodoId++
          });
          // ++++
          // reset the input field value
          this.input.value = '';
        } }>
          Add Todo
        </button>
        <ul>
          {this.props.todos.map(todo => 
            <li key={todo.id}>
              {todo.text}
            </li>
          )}
        </ul>
      </div>  
    )
  }
}


const render = () => {
  ReactDOM.render(
    <TodoApp todos={store.getState().todos} />,
    document.getElementById('root');
    )  
};

store.subscribe(render);
render();