Troubleshooting: CSS Styles not loading when passed as property in MUI withStyles

I am currently working on a react component that has a specific style defined as shown below:

const StyledInnerItem = withStyles((theme) => ({
  bgColor: {
    backgroundColor: (props) => {
      console.log('styledInnerItem color: ', props.color);
      return 'red';
    }
  }
}))(InnerItem);

My intention is to set the background color of the component based on the props.color value. However, I am facing an issue where it doesn't even return the temporary red color that I have set as the fallback option. When I check the logged props, it shows the correct color from the first render, and it gets added to the HTML file. However, the styles are only applied when I click on the component, resulting in the correct colors being displayed.

Everything works perfectly fine when the background color is not defined as a function. I need to achieve the same functionality by reading the color value directly from the props.

Answer №1

It is possible that the issue arises from the withStyles HOC only updating styles upon component re-render, without triggering a re-render with new props. One solution is to set the color value as a state in the component and update it when props change, prompting a re-render and style update.

Here's a way to implement this:

const StyledInnerItem = withStyles((theme) => ({
  bgColor: {
    backgroundColor: (props) => props.color
  }
}))(InnerItem);

class InnerItemWrapper extends React.Component {
  state = {
    color: 'red'
  };

  componentDidUpdate(prevProps) {
    if (this.props.color !== prevProps.color) {
      this.setState({ color: this.props.color });
    }
  }

  render() {
    return <StyledInnerItem color={this.state.color} />;
  }
}

This approach ensures that changes in props.color trigger a re-render, keeping styles updated accordingly.

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

Encountered an error while attempting to execute the command npx create react app: spawn UNKNOWN error occurred

After attempting to execute a basic npx create-react-app, an unexpected error occurred: D:\>npx create-react-app abc npx: installed 67 in 4.255s Creating a new React app in D:\abc. Installing packages. This might take a couple of minutes. In ...

AngularJS - Controller not recognizing state name parameter

I'm a newcomer to angular and struggling to understand why this specific issue is occurring. Interestingly, when I use {{$state.current.name}} in my view, everything works as expected. However, the problem arises when I attempt to pass it to my contr ...

Show text and image side by side on the same row

I am looking to showcase both image and text on the same line, similar to how it's done on tripadvisor.in/ <div style="display:inline-block"> <div style="display:inline;float:left"> <a href="CollegeProfile.php" class="white"> <h ...

Begin counting when a particular div element is visible on the screen

I have a plugins.init.js file that contains a try-catch block which runs on page load. I am looking for a way to execute this code only once when the div with the class counter-value comes into view. Is there a method to achieve this? try { const count ...

Pytest is not able to locate any elements on the webpage, yet the same elements can be easily found using the console

When using CSS or XPath in the console (F12), I am able to locate the element on the page. $$("span.menu-item[data-vars-category-name='Most Popular']") However, when trying to find the same elements with Selenium (pytest) using: driver.find_el ...

Having trouble with Tailwindcss in my Next.js App during the build process

I am currently in the process of developing a Chrome Extension using Nextjs. For guidance, I referred to an informative article at this link During testing in dev mode (npm run dev), everything related to tailwindcss functioned correctly. However, upon ...

Bootstrap arranges checkboxes into three evenly spaced columns and centers them within a form

Having trouble organizing my checkboxes into 3 columns and centering them within the form perfectly. Current layout: Click here for image Desired look: Click here for image HTML: ` <form action="/signup" method="POST" ...

Move the scroll bar outside of the div and set it to automatically overflow

My issue involves a small div with the CSS property overflow:auto;. However, when the scroll bar appears, it covers up a significant portion of the div. One possible solution is to use overflow:scroll;, but this can result in an unsightly faded scroll bar ...

Ways to upload an image beyond the Frontend directory

Currently, I have a react project with the following folder structure: - React Project - Frontend - src - public - data - Backend Typically, to load an image, I would place it in the Frontend/public/data folder and reference it in ...

Determining with jQuery if the right element has been successfully "dropped"

Imagine having 10 different draggable boxes and 2 droppable areas. You need to correctly match 5 boxes with droppable area 1 and the other 5 with droppable area 2. If a box intended for droppable area 1 is mistakenly dropped into area 2, it should not wor ...

What happens if I define both the left and right properties for spans?

This is a class for span with the CSS properties position:absolute; top:0px; left:0px; right:0px; .textStyle1 { font-size:24px; font-family:'Arial'; position:absolute; top:0px; left:0px; right:0px; } #div1 { position:absolute; lef ...

What steps can I take to stop my browser from displaying the "waiting for MyHostName" message while performing an ajax Post/Get operation?

Whenever I access a website using Chrome, a message appears in the status bar saying "Waiting for MyHost name" along with an Ajax Loader circle in the browser tab. Here is a javascript function that I am working with: function listen_backend_client_reques ...

Using Javascript to Implement Pinch Zoom on Android

After searching through the depths of the internet, I have yet to come across a viable solution or answer. The challenge at hand is the need to implement pinch zoom functionality for an element (specifically an image) using JavaScript in a Phonegap environ ...

Deliver integers using Express.js

When I try to send a response with Express using the code below, it doesn't work: res.send(13245) An error message is displayed: express deprecated res.send(status): Use res.sendStatus(status) instead src/x.js:38:9 (node:25549) UnhandledPromise ...

Properly Adding an External jQuery File in HTML Using jQuery

Seeking assistance as a newcomer to JS and programming in general. Currently working on a website where each page has its own HTML / PHP file, with jQuery and global JS functions included in the footer via a separate includes file "footer.php". Everything ...

Can the conventional HTML context menu be swapped out for a link context menu instead?

Currently, I am working on developing a custom linkbox component that is similar to the one found on this page: Here is an example of the code: export const Linkbox = ({}) => { const linkRef = useRef(null); return ( // eslint-disable-next-l ...

What are the typical architecture patterns used for Java/Kotlin Android apps in the Common App State

Which pattern is predominantly used for state management in Java or Kotlin Android applications? I am transitioning from React Native to Kotlin, where I solely relied on the React Redux architecture. What is the prevailing architecture being utilized tod ...

Ensure that the Bootstrap image element maintains its full height without resizing

While working on my Angular application, I encountered an issue with designing a side list-group of recent blogs using Bootstrap 4. When the aspect ratio is changed to mobile view, the images resize and become smaller to fit into the div as the title lengt ...

What is the best way to append something to the textContent property of an HTML tag within a markup page?

While working on resolving an XSS vulnerability in the jqxGrid where the cell content is rendered as HTML, I encountered a scenario like this: <a href="javascript:alert('test');">Hello</a>. To address this issue, I am exploring ways t ...

Creating dynamic PDFs with automatically adjusting heights in DOMPDF Learn how to make

It seems like this question may not have a straightforward answer, but let's give it a shot. My goal is to collect various information from users on my website and display it in an HTML template file that will later be converted into a PDF. With user ...