I have a list of ponents that I want to render when the user clicks a button. The screen is supposed to be a search screen where the user types in their query, and when they hit the search button a list of results is displayed. However, when I try to make a ponent render using the onPress, nothing happens. For this example I am just printing text instead of using map to print out ponents.
renderResults() {
return <Text> Doesn't get printed </Text>
}
render() {
return (
<View>
<Button
onPress={ this.renderResults.bind(this) } //use .bind(this) to access state in renderResults
title="Search!"
color="#841584" />
</View>
);
}
I have a list of ponents that I want to render when the user clicks a button. The screen is supposed to be a search screen where the user types in their query, and when they hit the search button a list of results is displayed. However, when I try to make a ponent render using the onPress, nothing happens. For this example I am just printing text instead of using map to print out ponents.
renderResults() {
return <Text> Doesn't get printed </Text>
}
render() {
return (
<View>
<Button
onPress={ this.renderResults.bind(this) } //use .bind(this) to access state in renderResults
title="Search!"
color="#841584" />
</View>
);
}
Share
Improve this question
asked Jun 22, 2017 at 17:33
user3624385user3624385
512 gold badges2 silver badges6 bronze badges
1
- You have to change the state of your ponent (or application) in the renderResults method. Now the renderResult method doen't trigger updating of state. If you'd like to change the state of ponent you have to call setState. – viktarpunko Commented Jun 22, 2017 at 17:37
3 Answers
Reset to default 9export default class App extends Component {
state={
isVisible:false
}
renderResults=() =>{
this.setState({
isVisible:!this.state.isVisible//toggles the visibilty of the text
})
}
render() {
return (
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
{this.state.isVisible?<Text> get printed </Text>:null}
<Button onPress={ this.renderResults}
title="Search!"
color="#841584" />
</View>
);
}
}
Try this code.
and you can run the demo on link
React doesn't know that it needs to rerender the view with this method. Instead, force a rerender by updating the local state. I would do something like state = {buttonPressed: false}
in the constructor and then this.setState({ buttonPressed: true}
in the onPress
. Then just have a simple boolean in the render to either return the text or the button depending on whether or not the buttonPressed
in the state is true or false
Simple eg. by @Max Millington answer. You can use Conditional rendering to check if state is true or false.
constructor () {
super();
this.state = {printText:false};
}
showText = () => {
this.setState({printText:true});
}
render() {
return (
<View>
<Button
onPress={() => this.showText() }
title="Search!"
color="#841584" />
{this.state.printText && <Text> Printed text... </Text> }
</View>
);
}