3

I have a list of components 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 component render using the onPress, nothing happens. For this example I am just printing text instead of using map to print out components.

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>
      );
  }

1
  • You have to change the state of your component (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 component you have to call setState. Commented Jun 22, 2017 at 17:37

3 Answers 3

9
export 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

Sign up to request clarification or add additional context in comments.

1 Comment

I dont understand whats wrong with this answer to downvote.
3

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

Comments

2

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>
  );
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.