React Native's setState function not causing a re-render

When using this component, the expected behavior is as follows: I press it, the selectedOpacity() function is called, the state is updated so it now renders with opacity=1.

However, for some reason, after calling this.setState, it is not re-rendering. I have to click the component again to make it re-render and apply the changes of opacity from the state.

export default class Category extends Component {

state = {
  opacity: 0.5
}

selectedOpacity() {
  // some stuff
  this.setState({opacity: 1})
}

render() {
 return(
  <TouchableOpacity style={[styles.container, {opacity: this.state.opacity}]} onPress={() => {
    this.selectedOpacity();
  }}>
  </TouchableOpacity>
 )
}

Answer №1

It appears that the issue lies in not binding selectedOpacity(), which could result in 'this' being undefined.

It would be advisable to assign state within a constructor for better organization.

constructor(props) {
    super(props);
    this.state = {};
    this.selectedOpacity = this.selectedOpacity.bind(this);
}

Furthermore, it is recommended to avoid creating arrow functions inside render due to performance implications. Instead, use the following approach: Link to more information.

onPress={this.selectedOpacity}

Answer №2

Modify selectedOpacity to an arrow function:

selectedOpacity = () => {
  this.setState({opacity: 1})
}

Next step:

onPress={this.selectedOpacity}

Update: According to the react documentation, this feature is considered experimental and uses the public class field syntax.

Answer №3

Consider changing the onpress attribute to

onPress={() => this.selectedOpacity()}

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

Excessive space consumption by children in MUI Grid

I am facing an issue with rendering two large blocks of text side by side, which may contain new lines or no whitespace. I have been using Material UI's Grid, but the grids are not behaving as expected. To illustrate my problem, I have provided a sma ...

What is the best way to dynamically adjust row sizes in react-bootstrap?

I have successfully created a grid of cards in groups of three using react-bootstrap. However, I am facing an issue where if one card's height is longer than the others, it creates unnecessary space and disrupts the layout of the entire row. You can s ...

Oops! There was an issue trying to solve the command "/bin/bash -ol pipefail -c npm run build" while deploying a Next.js app on Railway. Unfortunately, it did not complete successfully and returned an exit code of

[stage-0 8/10] RUN --mount=type=cache,id=s/8a557944-4c41-4e06-8de9-06bfcc5e8aaf-next/cache,target=/app/.next/cache --mount=type=cache,id=s/8a557944-4c41-4e06-8de9-06bfcc5e8aaf-node_modules/cache,target=/app/node_modules/.cache npm run build: 17.62 17.62 ...

What is the relationship between getStaticPaths and getStaticProps in Next.js?

Although I have gone through the Next.js docs and am familiar with getStaticProps and getStaticPaths, I'm still unsure about how they work in conjunction. Specifically, I'm curious about when exactly getStaticProps is triggered (particularly when ...

How to eliminate the blue border from a Select box in React using Material UI

I'm currently working on a project that includes a React Material UI Select component. I've successfully applied custom styles to it, but I'm facing an issue with a persistent blue outline around the Select box. This outline appears when the ...

Error message: "Window object not defined during NextJS build process."

Why am I encountering a 'window not defined' error? I haven't referenced window or document in my code, and it runs without issues during development but throws an error during the build process. ReferenceError: window is not defined at ...

React JS does not allow TextField and Select to change

I am relatively new to full stack development and I am currently working on a project to enhance my understanding of frontend development with React JS. While working on this project, I have been using Redux without any issues so far. However, I am facing ...

The issue of passing state in React Router v4 Redirect unresolved

I have a specific private route, /something, that I only want to be accessible when logged in. I've used Redirect with the state parameter set, however, when I try to access it at the destination, location.state is showing as undefined. Here is how I ...

Tips for Emulating Tab Behavior with the Enter Key on Material-UI Dialog Input Fields

In my React project utilizing Material-UI, I encountered a challenge with managing input focus within a dialog. Within the dialog, there are multiple input fields, and I aim to modify the default behavior so that pressing Enter shifts focus to the next inp ...

Implement ads.txt file for ReactJS project to improve performance and containerize the build process

After deploying a ReactJS project (optimized build) inside a Docker container, I encountered an issue while trying to enable Google ADS. The message I received indicated that the ads.txt file could not be found. I placed it in the /public folder and went ...

Tips for displaying a component using props obtained from the NextJS router

I'm attempting to display a component that utilizes a dynamic router path prop. My goal is for mysite.com/something to trigger the component with the something prop. If the route becomes mysite.com/somethingelse, I want the component to receive the so ...

What is the best way to vertically align a Material UI component to occupy the remaining space within a container

Issue with Material UI/Grids for Login Page As a newcomer to Material UI/Grids, I am currently working on creating a login page where the layout is split into two parts. The left side occupies 5 column spaces while the right side takes up 7 column spaces. ...

An error keeps popping up in the console saying "Module not found"

import React from 'react' import './sidebar.css' import logo from './images/' const sidebar = () => { return ( <div className='sideBar grid'> <div className='logoDiv flex&apo ...

Using two loops/arrays in JavaScript to generate a rating score

I want to create a simple rating component with the following appearance: ◼◼◼◻◻ (score: 3 out of 5) Here is my JSX code snippet: var score = 3; var range = 5; { [...Array(range)].map((e, i) => ( <div className="rating-item" ...

Using Next.js to fetch data with Suspense

As per the documentation, this code snippet demonstrates a common fetch with Suspense pattern (with some simplifications). import { getArtist, getArtistAlbums, type Album } from './api'; export default async function Page({ params: { username ...

Guide to utilizing Gatsby for showcasing a directory containing images and markdown files

Being new to Gatsby, react, GraphQL, and more unfamiliar technologies, I have primarily relied on pure CSS, HTML, and JavaScript for my website projects in the past. However, intrigued by the potential of Gatsby, I decided to step out of my comfort zone an ...

Ways to display a checked or unchecked checkbox in react depending on a boolean value obtained from an API

Is there a way to display a checked or unchecked checkbox in react jsx depending on a boolean value retrieved from an api? ...

Having trouble sending `req.params` through http-proxy-middleware in a NodeJS/Express application?

I'm still getting the hang of Node, and I've run into an issue with passing request parameters using http-proxy-middleware. Every time I try, I keep getting a 404 error. This is my express listener setup: app.put("/api/markets/:id",()=>{..c ...

React Router: Displaying a Sidebar on the Login Page

I'm trying to figure out how to hide my sidebar on the login page so only logged-in users can see it. Here's my code, but I can't seem to hide the sidebar... <BrowserRouter> <div className="container"> ...

Styling a div element in React

Just dipping my toes into the world of styling here, so bear with me. I'm currently working on a React app and attempting to bring an image from a file using the following code: import cup from './img/cup.png' My goal is to style it in co ...