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

Viewed 48888

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.

8 Answers

You can use state for dynamically change the text

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

export default class App extends Component{
constructor(){
    super();
    this.state = {
    textValue: 'Temporary text'
    }
    this.onPressButton= this.onPressButton.bind(this);
}

onPressButton() {
    this.setState({
        textValue: 'Text has been changed'
    })
}

render(){
    return(

<View style={{paddingTop: 20}}>
  <Text style={{color: 'red',fontSize:20}}> {this.state.textValue} </Text>
  <Button title= 'Change Text' onPress= {this.onPressButton}/>
</View>

   );
 }
}

With hooks:

import React, {useState} from "react";
import {Button, Text, View} from "react-native";

const App = () => {
  const [text, setText] = useState("Initial text");

  const onPressHandler = event => setText("Changed text");

  return (
    <View>
      <Text>{text}</Text>
      <Button title="Change Text" onPress={onPressHandler} />
    </View>
  );
};

Set my text in state method then update state in pressed button, then set in text like this:

<Text>
    {this.state.myText}
</Text>
import React, { useState } from "react";
import { View, Text } from "react-native";

const App = () => {
  const [value, setValue] = useState("Mohd Sher Khan");

  const hellod = () => {
    setValue("value changed");
    
  };

  return (
    <View>
      <Text onPress={hellod}>{value}</Text>
    </View>
  );
};

export default App;
Related