How to change text Value on button click in React Native?
I'm an iOS developer currently working on an experimental React Native app. I have the following code that 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 the text and the button However, when I click the button, the application crashes rather than showing the new text that should be shown. Im new to React Native, kindly advise me how to solve this error.
+3
source to share
5 answers
You can use state to keep the default text and then click to update state
import React, {Component} from 'react';
import {Text, Button} from 'react-native';
export default class App extends Component{
constructor(){
super();
this.state = {
textValue:'Change me'
}
}
onPress() {
this.setState({
textValue: "THE NEW TEXT GOES HERE"
})
}
render(){
return(
<View style={{paddingTop: 20}}>
<Text style={{color: 'cyan'}}>{this.state.textValue}</Text>
<Button title="Change Text" onPress={this.onPress}/>
</View>
);
}
}
+6
source to share
You can use this approach to update the value with one click of a button
class App extends React.Component {
constructor() {
super();
this.state = { val: 0 }
this.update = this.update.bind(this)
}
update() {
this.setState({ val: this.state.val + 1 })
}
render() {
console.log('render');
return <button onClick={this.update}>{this.state.val}</button>
}
}
0
source to share
You can use state to change text dynamically
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>
);
}
}
0
source to share