Modify the text color upon clicking with a TouchableOpacity component

Would appreciate help from experienced coders. I'm just starting out with coding and React. My goal is to be able to change the text color with a click, and then change it back to the original color with another click.

  function handleColorChange() {
    
      return (
        <Box>
          <Box>
            <TouchableOpacity>
              <Text>
                Change Color
              </Text>
            </TouchableOpacity>
        </Box>
      );
    }
    
    export default handleColorChange;

Answer ā„–1

To modify the text displayed on a button, you must establish styling for the <Text> element.

<Text style={{ color: /* insert state value here */ }}>Click Here</Text>

Illustration

The code snippet below is a variation of the Function Component illustration presented in the official documentation.

Reference: React Native / Docs / TouchableOpacity

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

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    paddingHorizontal: 10
  },
  button: {
    alignItems: "center",
    backgroundColor: "#DDDDDD",
    padding: 10,
    border: "thin solid grey"
  }
});

const App = () => {
  const [active, setActive] = useState(false);
  const onPress = () => setActive(!active);

  const buttonTextStyle = {
    color: active ? 'green' : 'red'
  };

  return (
    <View style={styles.container}>
      <TouchableOpacity
        style={styles.button}
        onPress={onPress}
      >
        <Text style={buttonTextStyle}>Click Here</Text>
      </TouchableOpacity>
    </View>
  );
};

export default App;

If you desire each button to function independently, you will have to introduce a new component.

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

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    paddingHorizontal: 10,
    gap: 10
  },
  button: {
    alignItems: "center",
    backgroundColor: "#DDDDDD",
    padding: 10,
    border: "thin solid grey"
  }
});

const StatefulButton = (props) => {
  const { color, activeColor } = props;
  const [active, setActive] = useState(false);
  const onPress = () => setActive(!active);
  const buttonTextStyle = {
      color: active ? activeColor : color,
      fontStyle: active ? 'unset' : 'italic',
      fontWeight: active ? 'bold' : 'normal'
    };
  return (
    <TouchableOpacity style={styles.button} onPress={onPress}>
      <Text style={buttonTextStyle}>Click Here</Text>
    </TouchableOpacity>
  );
};

const App = () => {
  return (
    <View style={styles.container}>
      <StatefulButton color="red" activeColor="green" />
      <StatefulButton color="magenta" activeColor="cyan" />
    </View>
  );
};

export default App;

Answer ā„–2

To begin, you need to import useState from the react library;

import React, {useState} from 'react';

    function lastTouches() {


const [active, setActive] = useState(false);
  const toggleColor = () => setActive(!active);

  const buttonStyle = {
    color: active ? 'green' : 'red'
  };

              return (
                <Box>
                  <Box>
                    <TouchableOpacity onPress={toggleColor}>
                      <Text style={buttonStyle}>
                        Change Color
                      </Text>
                    </TouchableOpacity>
                </Box>
              );
            }
            
            export default lastTouches;

By following these steps, you can successfully implement a button function in React JS;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The React Native Flatlist encountered an error due to a mismatch in function overloads

I'm currently working on a React Native app using Typescript, and I've encountered an issue with the Flatlist renderItem function. As someone who is new to both Typescript and React Native, I received the following error message: No overload ma ...

Switching a react virtualized table from JavaScript to TypeScript can uncover some type-related challenges

I have implemented the following demo in my React project: https://codesandbox.io/s/react-virtualized-table-checbox-stackoverflow-rbl0v?fontsize=14&hidenavigation=1&theme=dark&file=/src/App.js However, I am encountering issues with the code sni ...

Can PHP send a response to Ajax following a 500 error?

While my AJAX function is successfully sending data to a PHP file and displaying the response in my HTML, I have encountered occasional Error 500 responses from the PHP file. Despite knowing the cause of the error, I continue to call the AJAX function agai ...

Once the page is refreshed, the checkbox should remain in its current state and

I have a challenge with disabling all checkboxes on my page using Angular-Js and JQuery. After clicking on a checkbox, I want to disable all checkboxes but preserve their state after reloading the page. Here is an example of the code snippet: $('# ...

What sets $(document).on apart from ($ document).on in CoffeeScript?

One of my buddies is incorporating ($ document).on into his CoffeeScript script. I'm curious to know if this differs from the typical $(document).on and, if it does, how so? ...

Fulfill the specified amounts for each row within a collection of items

I have an array of objects containing quantities. Each object includes a key indicating the amount to fill (amountToFill) and another key representing the already filled amount (amountFilled). The goal is to specify a quantity (amount: number = 50;) and au ...

Retrieve the div element from the webpage

I've scoured the internet in search of a suitable technique, but unfortunately, I haven't had much luck. Essentially, I am interested in using JavaScript or jQuery (potentially with Ajax) to extract a specific word from a div on a page within my ...

Learn how to seamlessly update broken images on a webpage with a placeholder error image using the MooTools 1.2 framework

Currently working on a project with PHP, MySQL and utilizing Mootools 1.2 as the JavaScript framework. I am trying to find a way for all broken images to automatically be replaced with a designated error image. Any suggestions on how I can achieve this? ...

Error in the HTML DOCTYPE declaration affecting JavaScript files

My login page is displaying 5 errors, specifically a syntax error SyntaxError: syntax error <!DOCTYPE html> on 5 JavaScript files. After investigating, I discovered that these files are located in a non-public directory. Is there a way to exclude th ...

What is the best way to incorporate variables into the useState hook in React?

I want to create multiple useState hooks based on the length of the userInputs array. The naming convention should be userInput0, userInput1, userInput2,...userInputN. However, using "const [userInput+index.toString(), setUserInput] = useState('' ...

I encountered an error while trying to load the resource from http://premieroptie.nl/wp-content/themes/theme51771/favicon.ico: net::ERR_NAME_NOT_RESOLVED

Upon opening my website URL, computertechnet.nl, I noticed an error when inspecting and checking the console tab. The specific error message is: Failed to load resource: net::ERR_NAME_NOT_RESOLVED for . In addition, a second warning was displayed: G ...

Rotating arrows enhance the functionality of the accordion menu

I have successfully implemented a basic accordion with rotating arrows on click. Everything is working smoothly except for one issue: When I collapse one item and then try to collapse another, the previous arrow does not return to its default state. Is ...

Ways to update the select field without having to reload the entire page

I am working on a unique feature that involves two levels of drop down menus. When a user makes a selection in the first level, a corresponding set of options will appear in the second level. For example, I have 6 options in the first level, each with its ...

Encountering the "NextRouter was not mounted" error when utilizing the useRouter hook within a dynamically imported component in Next.js

Currently, I am working on a Next.js project and have run into an issue regarding routing and context management. My objective is to develop a page that dynamically displays event data based on the event_id extracted from the URL. However, Iā€™m facing the ...

Is there a way for me to revert back to my initial list after the 3rd click?

Front end development const [clientList, setClientList] = useState([]); //store all data from the database in a list //make an axios request to retrieve data from the database useEffect(() => { Axios.get("http://localhost:3001/clients&quo ...

Use CSS to apply hover effects to multiple sections of text at the same time

Is there a way in CSS to apply the hover state to one part of HTML text when another part is hovered over, both sharing the same class? I have a block of text in HTML that is broken down into individual words, each word linked to a specific CSS class. It ...

How can I send a value to an Angular element web component by clicking a button with JavaScript?

I want to update the value of an input in an Angular component by clicking on a button that is outside of the Angular Element. How can I achieve this in order to display the updated value in the UI? Sample HTML Code: <second-hello test="First Value"&g ...

Managing actions on dynamically generated dropdown options in <select> elements

If I have a function that generates a dropdown, it is called from a parent component where props like state key, array, and onChange function are passed in. The dropdown items are dynamically created from the array. What I want is for the parent's sta ...

Discovering the Sum of K with Node JS Value Mapping

Imagine you have a list of numbers like this: const arr = [{ key1: 10 }, { key2: 5 }, { key3: 7 }, { key4: 17 }];, and also a number k which is represented by const k = 17;. Your task is to determine if any two numbers from the list can be added up to equa ...

What is the reason behind classList returning 'undefined' unless getElementById is explicitly used?

Why is it that I can't seem to select multiple elements with the same class (using querySelector, querySelectorAll, getElementsByClassName, etc) and use classList to check if just one div contains a specific class? I've come across tutorials tha ...