I have two components. There is a button on ComponentA, when you click on it, it changes the state:
import ComponentB from './ComponentB'
.
.
constructor(props) {
super(props);
this.state = {
filter: true,
};
}
.
.
.
<TouchableOpacity
onPress={()=>{ this.setState({filter: !this.state.filter }); }}
>
{this.state.filter ?
<Text>Enabled</Text> :
<Text>Disabled</Text>
}
</TouchableOpacity>
.
.
.
<ComponentB filter={this.state.filter} />
ComponentB
render(){
return(
<View><Text>{this.props.filter}</Text></View>
);
}
Funny thing is, when you click on the button, the state does change and the text which is based on the state will also change. So at first time it changes from True
to False
. But ComponentB will receive still True
instead of False
.
When you click on it again, state changes from False
to True
, the text is also being shown correctly, but this time ComponentB will receive True
instead of False
.
Am I passing props to ComponentB wrong? Am I missing something?
Thanks in advance.
Move your setState out of the view;
import ComponentB from './ComponentB'
.
.
constructor(props) {
super(props);
this.state = {
filter: true,
};
}
changeFilter = () => { this.setState({filter: !this.state.filter }); };
.
.
.
<TouchableOpacity
onPress={()=> this.changeFilter(); }
>
{this.state.filter ?
<Text>Enabled</Text> :
<Text>Disabled</Text>
}
</TouchableOpacity>
.
.
.
<ComponentB filter={this.state.filter} />