Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native : how to change <Text> value dynamically

Tags:

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?

like image 332
Rushabh Rakholiya Avatar asked Dec 14 '16 09:12

Rushabh Rakholiya


People also ask

How do you change the text on a button press in react native?

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.


2 Answers

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; 
like image 97
Neel Gala Avatar answered Sep 21 '22 13:09

Neel Gala


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'}); } 
like image 23
Gogi Magogi Avatar answered Sep 19 '22 13:09

Gogi Magogi