0

The state of my application doesn't change after I press the button specified in the code.

import React from 'react'
import { View, Text, TextInput, Button} from 'react-native'

export default class App extends React.Component {
  constructor() {
    super()
    this.state = {
      text: '',
      displayText: true
    }
  }

  render() {
    return (
      <View>
      <TextInput
        onChangeText={(text) => this.setState({text})}
      />
      <Button
        onPress={(prevState) => this.setState({displayText: !prevState.displayText})}
        title="Display"
      />
      {this.state.displayText ? <Text>{this.state.text}</Text> : null}
      </View>
    )
  }

}

If the function passed to onPress is modified so that it changes displayText to false, it works as expected (it hides the text). Most likely the problem is in this portion.

<Button
        onPress={(prevState) => this.setState({displayText: !prevState.displayText})}
        title="Display"
/>

2 Answers 2

3
<Button
  onPress={(prevState) => this.setState({displayText: !prevState.displayText})} 
  title="Display"
/>

Is wrong, the prevState argument comes from setState as a function, but not from the onPress event :)

Should either be

<Button
  onPress={() => this.setState({displayText: !this.state.displayText})} 
  title="Display"
/>

or

<Button
  onPress={() => this.setState(prevState => {displayText: !prevState.displayText})} 
  title="Display"
/>
Sign up to request clarification or add additional context in comments.

Comments

0

Try this

<Button
        onPress={() => this.setState({displayText: !this.state.displayText})}
        title="Display"
/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.