How to change text Value upon Button press in React Native?

SeaWarrior404 picture SeaWarrior404 · Jul 11, 2017 · Viewed 36.7k times · Source

I'm an iOS developer currently working on an experimental React Native app. I have the following code which shows a button and sample text on the screen.

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

export default class App extends React.Component {
  constructor() {
    super();
    this.state = {sampleText: 'Initial Text'};
  }

  changeTextValue = () => {
    this.setState({sampleText: 'Changed Text'});
  }

  _onPressButton() {
    <Text onPress = {this.changeTextValue}>
      {this.state.sampleText}
    </Text>
  }

  render() {
    return (
      <View style={styles.container}>
        <Text onPress = {this.changeTextValue}>
          {this.state.sampleText}
        </Text>

        <View style={styles.buttonContainer}>
          <Button
            onPress={this._onPressButton}
            title="Change Text!"
            color="#00ced1"
          />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5deb3',
    alignItems: 'center',
    justifyContent: 'center',
  },
  buttonContainer: {}
});

The above code displays text and a button.

However when I click the button, the app crashes instead of showing the new text which is to be shown.

I'm new to React Native, kindly guide me on how to solve the error.

Answer

klendi picture klendi · Jul 12, 2017

You could use a state to keep your default text and then on press we update the state.

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

export default class App extends Component {
  state = {
    textValue: 'Change me'
  }

  onPress = () => {
    this.setState({
      textValue: 'THE NEW TEXT GOES HERE'
    })
  }

  render() {
    return (
      <View style={{paddingTop: 25}}>
        <Text>{this.state.textValue}</Text>
        <Button title="Change Text" onPress={this.onPress} />
      </View>
    )
  }
}