ReactJS: setState on parent inside child component

In your parent, you can create a function like addTodoItem which will do the required setState and then pass that function as props to the child component.

var Todos = React.createClass({

  ...

  addTodoItem: function(todoItem) {
    this.setState(({ todos }) => ({ todos: { ...todos, todoItem } }));
  },

  render: function() {

    ...

    return <div>
      <h3>Todo(s)</h3>
      {todos}
      <TodoForm addTodoItem={this.addTodoItem} />
    </div>
  }
});

var TodoForm = React.createClass({
  handleClick: function(e) {
    e.preventDefault();
    this.props.addTodoItem(this.state.todoInput);
    this.setState({todoInput: ""});
  },

  ...

});

You can invoke addTodoItem in TodoForm’s handleClick. This will do a setState on the parent which will render the newly added todo item. Hope you get the idea.

Fiddle here.

Leave a Comment