Tips for dynamically altering the background color of the body in React

Is there a way to dynamically change the background color of the body on certain pages using Redux state? I'm encountering an issue where the color specified in the store is not recognized when passed in the componentDidMount() function.

Here's my code:

componentDidMount() {
    this.props.list(this.props.match.params.page && decodeURIComponent(this.props.match.params.page));
    this.props.list_admin();
    document.body.style.backgroundColor = this.props.data_admin.backgroundColorFirst;
  }

componentWillUnmount() {
    this.props.reset();
    document.body.style.backgroundColor = null;
  }

const mapStateToProps = (state) => {
  return {
    data_admin: state.admin.list.data,
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    list_admin: (admin) => dispatch(list_admin(admin)),
    reset: () => {
      dispatch(reset());
      dispatch(success(null));
    },
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(List);

Given this setup, how can I ensure that the style is applied to the body when the color is defined in the 'data_admin' prop?

Thank you for your assistance.

Answer №1

Instead of simply changing the background color on initial mount and unmount, your current solution should also update when props change.

Consider utilizing the componentDidUpdate() lifecycle function for this purpose:

document.body.style.backgroundColor = this.props.data_admin.backgroundColorFirst;

This will ensure that the background color is adjusted whenever necessary.

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 promise was made but the function was never carried out

exports.index = function(req, res) { moviedb.indexMovie().then(function(){ console.log("DATABASE VALUES READ SUCCESSFULLY"); }); }; var moviedb = module.exports = { indexMovie : function() { return new P(function(resolve, reject){ ...

Error occurs while utilizing the cleaning autocomplete feature in React

I've developed a form using the material-ui library. Within this form, there's a textfield that incorporates an autocomplete feature which is populated using a useEffect to fetch data from an API and load the AUTOCOMPLETE functionality. Unfortun ...

Send the context parameter value of Unified Service Desk to a JavaScript web resource in CRM

Currently, I am working on CRM 8.2 and Unified Service Desk 4.1. I have a specific requirement where I need to pass parameter values from within Unified Service Desk Data Parameters to a JavaScript Webresource. I have come across some resources that sugge ...

Ways to separate a string based on changing values in Javascript

Given this unmodifiable string: "AAACCDEEB" I am looking to split it into an array whenever the value changes. In this scenario, I would end up with 5 arrays like so: [['A','A','A'], ['C','C'], [ ...

The getelementbyid function can only target and retrieve the information from the first ID within a PHP

I am facing an issue with a form embedded in a PHP while loop and processed by JavaScript using getelementbyid. When I submit the form, it only submits the first item on the loop. Below is my PHP code: $qsel = "SELECT * FROM sellbusiness ORDER BY sn DESC ...

Showing or hiding components within ReactJS based on conditions from other components

A custom hook has been created to toggle the visibility of a list when a button is clicked. Below is the snippet of the custom hook: import { useEffect } from "react"; import { useState } from "react"; function useVisibilityStatus() { ...

ui-grid-draggable-rows mistakenly identifies my data as a simple string

After successfully setting up the ui-grid-draggable-rows functionality by following the provided instructions, I encountered an error while running the code snippet from the example here. The error message I received is as follows: TypeError: this.spli ...

Accessing an object with keys as a React child in React Native can be achieved by utilizing the appropriate syntax

Trying to showcase the following JSON data: [ { "id":"1", "imagename":"dog" }, { "id":"2", "imagename":"cat" }, { "id":"3", "imagename":"mouse" }, { "id":"4", "imagename":"deer ...

Querying MongoDB with a JavaScript file for formatting datetime values

I am utilizing mongodb3.0.5 and my database collection appears as follows: { "_id" : "xxxxxxxxxxxxxxx", "SchoolId" : 1, "ActivationTimestamp" : ISODate("2015-09-22T13:01:58.000Z"), "PersonDetails" : [ { "Name" : "John" ...

Error Encountered: Ignored promise returned from the fetchData function was not handled

I've developed a component that retrieves data from an API. However, despite implementing a fetch function, I am unable to receive a response from the server. After waiting for approximately 2 minutes, I encounter a 503 error in the console. What migh ...

Python script to extract the link to a JavaScript file from the href tag in an HTML

Imagine a website similar to the following: This particular website contains links to pdf files referenced by an href tag in the page source, for example: <a href="javascript:$('form_cofo_pdf_view_B000114563.PDF').submit();">B000114563.PD ...

Guide to creating dependent form fields in ReactJS

I am currently working on developing an application similar to peer-to-peer lending platforms. To give you a better idea, here is a screenshot: Lending Application My goal is to dynamically link the input field for loan amount with a slider, so that they ...

Unable to receive data in an array with Vuejs

Here is the code snippet I am working with: let data = res.data.data; console.log('data: ', data) const list = []; for(let i = 0; i < data.length; i++){ console.log('data i: ', data[i]) //this line is not being printed in the ...

Is there a way to dynamically access BEM-style selectors using CSS modules?

For instance, I have this specific selector in my App.module.css file: .Column--active I want to access this selector from the App.js file in React using CSS modules. After importing all selectors from the CSS file as import styles from './App. ...

The parameter type `SetStateAction<EventDetails[] | undefined>` does not allow for assigning arguments

I am currently facing an issue in a ReactJS project where I am trying to update state that was initially set up like this: const [eventsData, setEventsData] = useState<EventDetails[]>(); Every time I try to update the state using setEventsData(obj), ...

Error message: Module 'next/babel' not found

After creating a new Next.js app using the "npx create-next-app" command and launching the server with "yarn dev", I encountered the following issue: reservations\frontend\node_modules\next\dist\compiled\babel\eslint-pars ...

Loading indicator displayed at the top of a div using JavaScript/jQuery

My current challenge involves implementing a progress bar, similar to the pace.js progress bar. The issue arises when the browser is refreshed, as the pace.js progress bar loads on top of the body instead of within a specified div. It is important that the ...

What are the steps to adjust the size of the Facebook "like" button?

Is there a way to modify the size of the Facebook like button? I attempted to adjust the padding of <a class="connect_widget_like_button clearfix like_button_no_like"> using jQuery, but was unsuccessful. Any suggestions on how this can be achieved? ...

When I attempt to run JavaScript code on the server, it fails to execute properly

When I run my code on my PC without putting it on the server, it works perfectly fine. However, when I upload it to the server and try to call it, I encounter the following error: Uncaught ReferenceError: crearLienzo is not defined at onload ((index): ...

SVG utilizes a distinct color for every individual path

I have an SVG file containing two different paths. <path d="M 84.4 53.2 C 75.3 50.1 67.1 48.5 59.6 48.3 C 51.2 48 45.2 47.5 41.5 46.5 C 35.7 45.1 29.9 42.4 23.9 38.4 C 21.6 36.9 19.4 35.2 17.3 33.2 C 19.4 34.2 21.6 35 23.9 35.6 C 27.3 36.5 34.1 37 44 ...