React Native program to change the value of a text on button click

Introduction :

In this tutorial, I will show you how to change the value of a text dynamically in react native. We will use one button, on click we will change the value of a Text. For this example, I am using hook to manage state.

Example program :

Create one basic react native example program and use the below code in your App.js file :

import React, {useState} from 'react';
import {StyleSheet, Text, View, TouchableOpacity} from 'react-native';

export default function ExampleProgram() {
  const [value, setValue] = useState(1);

  const incrementValue = () => setValue(value + 1);

  return (
    <View style={styles.container}>
      <Text style={styles.text}>{value}</Text>
      <TouchableOpacity style={styles.touchable} onPress={incrementValue}>
        <Text style={styles.touchableText}>Click here</Text>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    margin: 12,
  },
  touchable: {
    alignItems: 'center',
    backgroundColor: '#7986cb',
    padding: 10,
    marginTop: 30,
    borderRadius: 10,
  },
  touchableText: {
    color: 'white',
    fontSize: 20,
  },
  text: {
    color: 'black',
    fontSize: 40,
  },
});

Explanation :

  1. The current value of the variable value is we are showing to the user.
  2. The start value of the variable value is 1. We are using setValue to assign it.
  3. incrementValue increments the value of the variable value by 1. We are showing it in a Text component.
  4. We are using TouchableOpacity as like a button. On click, it calls incrementValue to increment value.

Output :

If you run this program, it will give the below output :

React Native change text button click

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊❤️❤️