Reputation: 1250
I'm passing a function from Parent to Children components using FlatList but for some reason, the error occurs that undefined is not a function referring to updateState
function.
Here's the parent component:
class Home extends Component {
/*
data items here
*/
updateState(data) {
this.setState({ data: data });
}
renderItem() {
return (
<ItemView updateParentState={ (data) => this.updateState(data) } />
)
}
render() {
return (
<FlatList
style={styles.fragmentContainer}
data={this.state.items}
keyExtractor={(item, index) => index.toString()}
renderItem={this.renderItem} />
)
}
}
Here's the child view:
class ItemView extends Component {
constructor(props) {
super(props);
this.state = {
data: "some data"
};
}
render() {
return (
<TouchableOpacity onPress={ () => this.props.updateParentState(this.state.data) }>
<Text>Item name here</Text>
</TouchableOpacity>
)
}
}
Upvotes: 0
Views: 153
Reputation: 9674
This should fix your problem:
render() {
return (
<FlatList
style={styles.fragmentContainer}
data={this.state.items}
keyExtractor={(item, index) => index.toString()}
renderItem={this.renderItem.bind(this)} />
)
}
You should always use the .bind(this)
function if you're going to pass a function as props so that this
does not get lost. Or you could use the arrow function if you're not a fan of .bind
.
Ex:
{() => this.renderItem()}
Upvotes: 1