React Native : how to change <Text> value dynamically

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

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;

Tags:

React Native