I want to change value dynamically at some event
Event:
BackgroundGeolocation.on('location', (location) => { currentDistance = distance(previousLatitude,previousLongitude,latitude,longitude); this.setState({ text: currentDistance }); }); <Text> Moving : {this.state.text} </Text>
does anyone know how to change text or any other method to achieve?
To change a button's text on click in React:Track the text of the button in a state variable. Set the onClick prop on the button element. When the button gets clicked, update the state variable.
Below is the example where it uses states for dynamic changing of text value while clicking on it. You can set on any event you want.
import React, { Component } from 'react' import { Text, View } from 'react-native' export default class reactApp extends Component { constructor() { super() this.state = { myText: 'My Original Text' } } updateText = () => { this.setState({myText: 'My Changed Text'}) } render() { return ( <View> <Text onPress = {this.updateText}> {this.state.myText} </Text> </View> ); } }
EDIT: Using React Hooks
import React, { useState } from 'react'; import { View, Text } from 'react-native'; const ReactApp = () => { const [myText, setMyText] = useState("My Original Text"); return ( <View> <Text onPress = {() => setMyText("My Changed Text")}> {myText} </Text> </View> ) } export default ReactApp;
Use:
<TextInput editable={false} ref={component=> this._MyComponent=component}/>
instead of:
<Text></Text>
Then you can change the text this way:
onPress= {()=> { this._MyComponent.setNativeProps({text:'my new text'}); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With