gpbaculio
gpbaculio

Reputation: 5968

How to pass a value to my parent React component from input type?

I have this in my parent TodoList component:

state = {
  checkedIds: []
}
_handleSelectedTodo = (e) => {
  e.preventDefault(); 
  this.setState({checkedIds: [...this.state.checkedIds, e.value]});
}

the _handleSelectedTodo is passed as props to Todo component like this

<Todo
  key={edge.node.id}
  todo={edge.node}
  viewer={this.props.viewer}
  handleSelectedTodo={this._handleSelectedTodo}
/>

Now below is the code of my Todo component:

<li>
  <input
    checked={this.props.todo.complete}
    className="toggle"
    onChange={this.props.handleSelectedTodo.bind(null)}
    type="checkbox"
    value={this.props.todo.id}
  /> 
  {this.props.todo.text+' - '+this.props.todo.complete}

I want to pass the value here to parent as e.target.value but I cannot succeed changing the state of my TodoList parent checkedIds. Help?

Upvotes: 1

Views: 423

Answers (2)

Milan Panigrahi
Milan Panigrahi

Reputation: 546

Child

<input type="text" onChange={event => this.props.onInputChange(event.target.value)}/>

Parent

onInputChange(filter){
    console.log(filter)
  }


<child onInputChange ={this.onInputChange.bind(this)}/>

Upvotes: 0

Yichz
Yichz

Reputation: 9681

first it should be e.target.value instead of e.value

_handleSelectedTodo = (e) => {
  // here add your logic for update the completed flag depending on the value of the id 
  this.setState({checkedIds: [...this.state.checkedIds, e.target.value]});
} 

to pass the callback is without bind (since you already used arrow function in todoList)

<input
    checked={this.props.todo.complete}
    className="toggle"
    onChange={this.props.handleSelectedTodo}
    type="checkbox"
    value={this.props.todo.id}
  /> 

additionally, I think you still need to handle when checkbox is unchecked (removed from the array)

https://codepen.io/kossel/pen/XRZPdK

Upvotes: 1

Related Questions