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

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


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


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


You better make sure what _onPressButton() is doing. You can simply setState() in this function and do nothing else, which can help you solve the problem. If you want to render something new, you have to add return() and wrap up Text.