Working with ReactJS and having trouble understanding how callback functions
work with ReactJS.
I have a parent component titled TodoFormComponent
, which initializes my list of todo items. I've created a callback function on the TodoItemsComonent
, but it doesn't trigger the updateItem
method and display the selected
item.
Question: How can I pass data from the child to the parent? I want to pass the selected todo item to the parent so that I can update the master todo list.
Parent Component (TodoFormComponent)
The TodoFormComponent
has selectedTask
, which should be triggering the updateItem
method.
import * as React from "react";
import TodoItemsComponent from "../todo-items/todo-items.component";
import AddTodoItemComponent from "../add-todo-item/add-todo-item.component";
export default class TodoFormComponent extends React.Component {
constructor(){
super();
this.state = {
todoItems: [
{ id: '1', todo: 'First Todo Item' },
{ id: '2', todo: 'Second Todo Item' },
{ id: '3', todo: 'Third Todo Item' }
],
selected: {}
};
this.updateItem = this.updateItem.bind(this);
}
updateItem () {
console.log('Selected Value:: ', this.state.selected);
}
render() {
return (
<div className="row">
<div className="container">
<div className="well col-xs-6 col-xs-offset-3">
<h1>To do: </h1>
<div name="todo-items">
<TodoItemsComponent items={this.state.todoItems} selectedTask={() => {this.updateItem}}/>
</div>
<div name="add-todo-item">
<AddTodoItemComponent/>
</div>
</div>
</div>
</div>
)
}
}
Child Component (TodoItemsComponent)
The TodoItemsComponent
has an onClick
to update the selected value. This gets updated in the selectedTask
function.
import * as React from "react";
export default class TodoItemsComponent extends React.Component {
constructor(props) {
super(props);
}
selectedTask (item) {
this.setState({selected: item})
}
render() {
return (
<ul className="list-group">
{
this.props.items.map((item) => {
return (
<li className="list-group-item">
{item.todo}
<div className="pull-right">
<button
type="button"
className="btn btn-xs btn-success">
✓
</button> <button
type="button"
className="btn btn-xs btn-danger"
onClick={() => {this.selectedTask(item)}}
>X
</button>
</div>
</li>
)
})
}
</ul>
)
}
}