React state binding from child to parent

I am new to reactjs

I have a JSON array that consists of a task. I passed the array to a 2 ul list. One completed tasks and the other completed unfinished tasks. If I click on a task, the status changes but not updated in the other item. However, if I enter any text in the input state, then other items are set. Why isn't the state immediately set when I click on a task?

<script src=""></script>
<script src=""></script>

<div id="todo">
<script type="text/jsx">
    var TodoList = React.createClass({
        clickHandle: function(index) {
            this.setState({items: this.props.items});
        render: function() {
          var createItem = function(itemText, index) {
                return <li key={index} onClick={this.clickHandle.bind(this,index)}>{itemText.text}</li>;
          return <ul>{, this)}</ul>;
      var TodoApp = React.createClass({
        getInitialState: function() {
          return {items: [{"text":"1true","completed":true},{"text":"2true","completed":true},{"text":"1false","completed":false}], text: ''};
        onChange: function(e) {
        handleSubmit: function(e) {
              var nextText = '';
              this.setState({items:this.state.items,text: nextText});
            alert("Enter some text!");
        render: function() {
          return (
              <TodoList items={this.state.items} completed={false}/>
              <TodoList items={this.state.items} completed={true}/>
              <form onSubmit={this.handleSubmit}>
                <input onChange={this.onChange} value={this.state.text} />
                <button>{'Add #' + (this.state.items.length + 1)}</button>

      React.render(<TodoApp />, document.getElementById('todo'));





source to share

1 answer

This is because the parent TodoApp component that displays two lists does not know that something has changed in one of them. To do this, the child component must notify the parent component about it.

Add onStatusUpdate attribute for TodoList like this

<TodoList items={this.state.items} completed={false} onStatusUpdate={this.update}/>


This is how the update method can be determined

update: function(items){
  this.setState({items: items});


In the click handler of the child component, do something like this

clickHandle: function(index {
  this.props.onStatusUpdate(this.props.items); // <-- this triggers the onStatusUpdate attribute defined in TodoList component


Here is an updated demo `



All Articles