Can a child method have change handler in React?

Tags: , , ,



I was wondering why the child component with the changed value is not getting rendered here.

Isn’t it a good idea to have a child handle its own changes or better to have the controller in the parent?

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      todos: todosData
    };
  }
  render() {
    const todoItems = this.state.todos.map(item => (
      <TodoItem key={item.id} item={item} />
    ));
    return <div className="todo-list">{todoItems}</div>;
  }
}

This is the Child TodoItem

class TodoItem extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isComp: {}
    };
    this.handleChange = this.handleChange.bind(this);
  }
  handleChange() {
    let tempObj = this.state.isComp;
    tempObj.completed = !this.state.isComp.completed;
    this.setState = { isComp: tempObj };
    console.log(this.state.isComp);
  }
  render() {
    this.state.isComp = this.props.item;
    console.log(this.state.isComp);
    return (
      <div className="todo-item">
        <input type="checkbox" checked={this.state.isComp.completed} />
        <p>{this.props.item.text}</p>
      </div>
    );
  }
}

As you can see the state is changed with handleChange() but this does not fire the render. I am also not too sure if another object can be assigned to an object of the state (let tempObj = thi.state.isComp).

The functionality I am trying to achieve is check and uncheck a box and render accordingly.

Answer

What is this?

this.setState = { isComp: tempObj };

I think it should be

this.setState({ isComp: tempObj });


Source: stackoverflow