Reputation: 958
I have a callback function in a parent component passed to an child component that should retrieve the input once submission in the child component takes place but is not working as expected. No data is being retrieved by the parent. Here is my code:
Parent:
class App extends Component {
constructor(props) {
super(props)
this.state = { item: '' }
}
getItem(item) {
this.setState({
item: item
})
console.log(this.state.item);
}
render() {
return (
<div className="App">
<Input getItem={this.getItem} />
<h2>{this.state.item}</h2>
</div>
);
}
}
Child:
class Input extends Component {
constructor(props) {
super(props)
this.state = { value: '' }
this.handleChange=this.handleChange.bind(this);
this.handleSubmit=this.handleSubmit.bind(this);
}
handleChange(e) {
this.setState({
value: e.target.value
})
console.log(this.state.value)
}
handleSubmit(e) {
{this.props.getItem(this.state.value)};
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>
<input type="text" name={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="+" />
</form>
</div>
)
}
}
Upvotes: 1
Views: 35
Reputation: 87
Solution 1 :
Use fat arrow in getItem
function like this :
getItem = (item) => {
this.setState({
item: item
})
console.log(this.state.item);
}
Solution 2 :
Bind getItem
function in counstructor like :
constructor(props) {
super(props)
this.state = { item: '' }
this.getItem = this.getItem.bind(this);
}
Solution 3 :
Bind getItem
function in input directly :
<Input getItem={this.getItem.bind(this)} />
Upvotes: 1
Reputation: 652
You should bind the getItem
context to the App
class.
You can do this by doing
<Input getItem={this.getItem.bind(this)} />
or by using the arrow function when you define getItem
or by binding the method in the constructor as you did for the child component
Upvotes: 0