React Native tutorial: Changing button color on press

When a user clicks on the TouchableOpacity element, I want to change the color of the button from the default gray to blue. Initially, the 'checked={this.state.newProjects}' newProjects variable is not present in the state, so when clicked it should create a new variable and set the 'checked' prop to true, causing the color change. The goal is to toggle the button color with each press. The code below is an attempt to achieve this, based on a similar example in React Native: https://codesandbox.io/s/k3lzwo27z5.

Code:

constructor(props) {
        super(props);
        this.state = {

        };
    }

    handleClick = e => {
    this.setState({
        [e.target.name]: !this.state[e.target.name]
    });
};

<TouchableOpacity onPress={this.handleClick('newProjects')}>
                        <Filterbutton name="New Projects" checked={this.state.newProjects}/>
                    </TouchableOpacity>

Filterbuttonjs:

const Filterbutton = ({name, checked}) => (
    <View style={checked ? styles.buttonTab : styles.defaultButtonTab}>
        <Text style={styles.buttonContent}>{name}</Text>
    </View>
)

export default Filterbutton;

const styles = StyleSheet.create({
    defaultButtonTab: {
        justifyContent: 'center',
        alignItems: 'center',
        maxWidth: 150,
        height: 30,
        padding: 10,
        borderRadius: 13,
        borderStyle: "solid",
        borderWidth: 1.3,
        borderColor: "rgba(131, 143, 158, 0.7)",
        marginRight: 10,
        marginTop: 10
    },
    buttonTab: {
        justifyContent: 'center',
        alignItems: 'center',
        maxWidth: 150,
        height: 30,
        padding: 10,
        borderRadius: 13,
        borderStyle: "solid",
        borderWidth: 1.3,
        borderColor: "#1994fc",
        marginRight: 10,
        marginTop: 10
    },

Screenshot:

https://i.sstatic.net/l87FH.png

Answer №1

The button's color should be specified within the <Text> element, not in

<View>
  <Text style={[styles.text, checked ? styles.btnChecked : '']}>{name}</Text>
</View>

Answer №2

In order to properly set up newProjects, it needs to be declared within the state.

Code:

constructor(props) {
        super(props);
        this.state = {
             newProjects=''
        };
    }

ALSO make sure to update your null check like so.

 <View style={!checked ? styles.defaultButtonTab :styles.buttonTab }>

Answer №3

Here lies the issue:

onPress={this.handleClick('newProjects')}

onPress requires a function as its argument, not the result of an executed function. By using this.handleClick('newProjects'), you are executing the function here. Instead, onPress should execute the function name provided. Let me explain further:

onPress={this.handleClick}

This will trigger your function when clicked/tapped, as it is the default behavior. Your handleClick function should then look like this:

handleClick = (e) => {
  //do stuff
}

If you need to pass a value from the component level, a better approach would be:

onPress={(v) => this.handleClick(yourValue)}

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

Understanding the distinction between .navbar and .navbar a in CSS

Can you explain the distinction between .navbar and .navbar a? .navbar { overflow: hidden; background-color: #333; font-family: Arial; } .navbar a { float: left; font-size: 16px; color: white; ...

What is the best way to access the URLs of files within a Google Drive folder within a React application?

I've been working on a react app that's relatively straightforward, but I plan to add a gallery feature in the future. To keep things simple for the 'owner' when updating the gallery without implementing a CMS, I decided to experiment ...

Change a TypeScript alias within the @types namespace

While using Typescript 3, I encountered a situation where I needed to modify a type alias from the @types/json-schema definition provided by DefinitelyTyped. The issue arose when I wanted to incorporate a custom schema type into my code. Since this custom ...

simulated using useDispatch in jest to verify the parameters by testing the dispatched action within a functional component

Greetings! I am currently working on writing tests for a functional component using Jest and Enzyme. I have encountered an issue where simulating a click event leads to a change in the component's state (using useState), triggering a useEffect call th ...

Implement Next.js deployment on NGINX server with a 403 forbidden error

I am currently utilizing Next.js for the frontend and Django for the backend. During development, everything is functioning properly. However, when transitioning to production, I am encountering a 403 Forbidden Error related to /_next/static/chunks. It app ...

AJAX Post Request Function without Form That Does Not Reset

I am currently struggling with understanding the Ajax POST method. I am attempting to make an API request, and since the response has similar parameters, I decided to create a global function that can be used by other HTML/JS pages. However, I am aware tha ...

"Prisma vs. Supabase: A Comparison of Image Uploading

I am encountering an issue with adding image URLs to the Prisma database. I have successfully uploaded multiple images from an input file to Supabase storage, but when I try to add their URLs to the database, I receive an error regarding property compatibi ...

Utilizing JavaScript to call functions from an ASP.NET code file

I am in need of assistance with integrating a JavaScript-based timeline that requires data from an SQL server. I have already developed the queries and JSON conversions using C#.NET functions within a code file associated with an .aspx page. As a newcomer ...

Utilizing Three.js to Upload Images and Apply Them as Textures

While attempting to upload an image via URL and set it as a texture, I encountered an issue. The error message THREE.WebGLState: DOMException: Failed to execute 'texImage2D' on 'WebGLRenderingContext': Tainted canvases may not be loaded ...

Unable to establish connection via web socket with SSL and WSS in JavaScript

Below is the code I used to implement web socket: try { console.log('wss://' + hostname + ':' + port + endpoint); webSocket = new WebSocket(webSocketURL); webSocket.onmessage = function (event) { //c ...

Is there a way to align both JSX elements in a single row without having one overlap the other?

Is there a way to showcase both conditions side by side on the same line? If Condition 1 is met, display the images; if Condition 2 is met, show the video. import React, { useState } from "react"; import { Card } from "react-bootstrap" ...

What is the reasoning behind AngularJS 2 HTTP Post only allowing string data as input?

Can someone explain to me why the HTTP Post method in AngularJS 2 (2.0.0-beta.13) only accepts string data as body, unlike in AngularJS 1 where it can accept a JavaScript object? AngularJS-1: $http.post(someUrl,someObject) AngularJS-2: http.post(someUr ...

What is the best way to configure maxSockets in Node.js while working with Express?

Can the maximum number of sockets in Node.js be adjusted while working with the Express framework? More information can be found here. ...

React-navigation installation in React Native project failed due to ENOENT error - file or directory does not exist

Encountering errors during the installation of react-navigation in my react native project using npm install @react-navigation/native https://i.sstatic.net/uKiPQ.png The installation process reaches halfway, pauses for a few minutes, and then displays an ...

Issue with ngStyle function in Internet Explorer

Within my Angular 4 application, I have defined styles as shown below: [ngStyle]="{'border': getInterleaveColor(i)}" The following function is also included: getInterleaveColor(auditNumber) { var borderProperties = '2px solid'; ...

Change a portion of the CSS background-image URL using vanilla JavaScript for a set of pictures

My current code successfully updates part of an src URL for regular images. let svgz = document.querySelectorAll(".svg"); for (let i = 0; i < svgz.length; i++) { svgz[i].src = svgz[i].src.replace("light", "dark"); } Now, ...

Storing Radio Buttons and Checkboxes Using LocalStorage: A Simple Guide

Is there a way to save and retrieve values from localStorage for input types "radio" and "checkbox"? I've tried using the same code that works for text and select elements, but it doesn't seem to be saving the values for radio and checkbox. Can s ...

Displayed unfamiliar Obj characters on Google Chrome

Hey there, I'm new to Vue JS and Vuetify and could really use some help! I've been trying to display some HTML content from my data using v-html in Vue JS, but for some reason, strange OBJ symbols keep showing up. Here is a screenshot of what I ...

What could be causing my page's wrapper to shrink upon logging in?

After logging out, the background of my page wrapper expands to cover 100% of the page. However, once you log back in, it shrinks and adjusts to the width of the member bar... TO TEST USER ACCOUNT BELOW: USERNAME: TEST PASSWORD: TEST123 HTML FOR LOGGED ...

Label Overlapping Issue in React Select

Utilizing react-select version ^5.1.0, I am encountering an issue where the word "select" overlaps with the options when scrolling. An image has been attached for better clarification. How can I eliminate the occurrence of the select word overlapping my op ...