Attempting to modify background by manipulating the state in Reactjs

I'm currently working on an app that features various games. My goal is to allow users to click a button and have the game display on the screen, with the background color changing as well. I aim to utilize state to control the overall background of the entire app, not just the game component.

However, I'm encountering an issue where the state changes when the game is displayed, but the page does not update accordingly. Any suggestions?

Here's a glimpse of my current state setup:

state = {
  madLibsOut: false,
  ticTacOut: false,
  pigLatinOut: false,
  background: "green",
}

Below is an example of my attempt to make a change. Although the state updates successfully and the game is displayed, the background color fails to update:

handleClickTicTacToe = () => {
  const out = this.state.ticTacOut
  const newColor = 'red'
  this.setState({ ticTacOut: true, background: newColor })
}

For reference, here's how I am applying the style:

appStyle={
  backgroundColor: this.state.background,
  height: "100vh",
  width: "100%",
}

render() {
  return (
    <div className="App" style={this.appStyle}>

Any help or advice would be greatly appreciated. Thank you!

Answer №1

Your problem lies in the way you are setting your state as a class variable. This results in it being instantiated only once, with the value remaining unchanged.

If you are using ES6, it is recommended to follow a similar approach as suggested by @Allessandro Messori. However, it is not ideal to modify the object property and then set the state in his solution.

When setting the state, it is generally better to create a new object to update the state. In this scenario, your style object should be a new object.

state = {
  madLibsOut: false,
  ticTacOut: false,
  pigLatinOut: false,
  appStyle: {
    backgroundColor: "green",
    height: "100vh",
    width: "100%",
  } 
}

handleClickTicTacToe = () => {
  const out = this.state.ticTacOut
  // Use Object.assign(this.state.appStyle, { backgroundColor: 'red' }); if no ES6 enabled
  const newStyle = { ...this.state.appStyle, backgroundColor: 'red' }; 
  this.setState({ ticTacOut: true, appStyle: newStyle })
}

render() {
  return (
    <div className="App" style={this.state.appStyle}>

Alternatively, you can create a function that returns your style, ensuring it always updates based on your state. If you stick to your original code, you can update it as follows.

getAppStyle = () => {
  return {
    backgroundColor: this.state.background,
    height: "100vh",
    width: "100%",
  };
}

render() {
  const style = this.getAppStyle();
  return (
    <div className="App" style={style}>

Answer №2

Transform appStyles into a dynamic function that generates a style object according to the current state.

appStyles = () => {
    return {
        color: this.state.textColor
    }
}

Answer №3

To better organize your code, consider moving all the properties of the appStyle object into your component's state.

You can achieve this by setting up your state like this:

  state = {
     madLibsOut: false,
     ticTacOut: false,
     pigLatinOut: false,
     appStyle:{
     backgroundColor: "green",
     height: "100vh",
     width: "100%",
    }
 }


  handleClickTicTacToe = () => {
    const out = this.state.ticTacOut
    let appStyle = this.state.appStyle
    appStyle.backgroundColor = 'red'
    this.setState({ticTacOut: true, appStyle:appStyle})
 }

  render() {
   return (
      <div className="App" style={this.state.appStyle}>

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

Tips on customizing the appearance of the "time" input type

Are there any resources that explain how to style the input type "time" completely? I have been searching but unable to find a comprehensive guide with all the necessary style attributes! The only example I came across is: input[type="time"]{ /**styl ...

What is the best way to stop a series of Ajax promises from continuing?

Managing multiple ajax requests that are dependent on each other can be tricky, especially when you need to stop the chain if one of the requests returns false. Check out this sample code snippet below: // Implementing a promise chain return this.getBan ...

Is there a way to cancel hiding on a q-dialog?

I'm currently working on integrating a confirmation modal within a dialog box that includes form input fields. The purpose is to alert the user when they try to exit without saving their changes. The modal should appear every time the user modifies th ...

Excessive messages are being sent to the child process from the nodejs/electron stream

When trying to send messages from an Electron frontend to a C++ child process via stdin upon button press, I encountered an issue where multiple identical sends were triggered with each click. What is the recommended approach to prevent redundant messages ...

Troubleshooting issue: Failure in proper functionality of Jquery's slideDown

My form is divided into 3 sections, with the latter two initially hidden using CSS. When users click the next button in the first section, the second section is supposed to slide down into view. However, I'm experiencing an issue where the animation s ...

Experiencing issues setting up npx to create a React app called my-app

the aforementioned errors indicate a potential issue with npm, although I am not certain. The error messages are as follows: at Function.Module._resolveFilename (node:internal/modules/cjs/loader:985:15) at Function.Module._load (node:internal/modules/cjs/l ...

Can you explain the definition of "mount" in the context of Express?

Currently diving into the world of Express.js, I stumbled upon this definition: "An Express router offers a limited set of Express methods. To initialize one, we call the .Router() method on the main Express import. To utilize a router, we mount it a ...

I am looking to display multiple divs sequentially on a webpage using JavaScript

Looking to display a rotating set of alerts or news on my website. The goal is to show each news item for a certain number of seconds before moving on to the next one in line. However, I'm new to javascript and need help creating a code that will cont ...

Preventing list refresh over API following drag & drop using the elegant Drag and Drop library

I replicated my issue with Context and DND on this sandbox: https://codesandbox.io/s/adoring-booth-33vqo. I plan to incorporate additional components into this example, utilizing a Context hook for value-sharing throughout the page. Initially, everything ...

React- Is it possible to update the state upon clicking a new page?

Within my application, there is a collection of cards featuring character images and descriptions sourced from an API. It is my responsibility to implement client-side pagination to limit the number of cards displayed on-screen at any given time. Below is ...

Passing references in React to parent components

Struggling to adopt the react way of thinking, I'm facing an issue with invoking the .submit() method of the form component. Within a material-ui Dialog, buttons are passed via the actions property. Now, I need to trigger the .submit() method of the ...

Crystal-clear TextField component in Office UI Fabric

Seeking advice on how to clear a masked text field from Office UI Fabric using a button. Does anyone have a solution for this? I attempted to set the value using a state, but unfortunately, it did not work as expected. ...

What is the reason for the presence of "e034" in CSS not resulting in the creation of a tick icon?

Here is the CSS code I am using: <style> .icons:before { content: "\e034"; color: #00bc9b; font-size: 16px; margin-top: -1px; margin-left: -1px } </style& ...

playing with JSON data in angular

Currently, I am utilizing AngularJS and making use of $http.get to fetch a JSON response which I then assign to $scope.myObjects. After implementing ng-repeat="object in myObjects" in the HTML, everything seems to be functioning properly. My query pertai ...

Transferring information within React components

Looking for some assistance with the code below. I'm facing an issue where the data is not being submitted along with the form, even though the correct values are displayed in the form. I have included a user query to fetch data from another object an ...

Maximizing memory efficiency in Javascript through array manipulation strategy

In the project I am working on, I maintain a history of changes. This history is stored as an array containing objects, each with two arrays as properties. When adding a new history snapshot, it appears as follows: history.push({ //new history moment ...

What is the best way to handle returning a promise when outside of the scope?

I am currently working on retrieving multiple files asynchronously from AWS S3 by utilizing Promises in my code. Although I'm using AWS S3 for fetching the files, there seems to be an issue with fulfilling the promises as it's out of scope and c ...

What is the best way to retrieve a {collection object} from a JavaScript map?

My application utilizes a third-party library that returns the map in the following format: public sids: Map<SocketId, Set<Room>> = new Map(); When I try to access it using the code below: io.of("/").adapter.sids.forEach(function(va ...

Implementing pagination in a table with the help of jQuery

I've been working on this code for the past few days and I'm struggling to find a solution that meets my requirements. What I need is pagination within a specific section of a table, with the following actions/events: When clicking previous o ...

Ways to split up array objects in an axios GET request

Hello, I recently implemented an AXIOS GET request that returns an array of objects. However, the current example I am using retrieves the entire array at once, and I need to separate the objects so that I can work with them individually. class CryptoAP ...