The renderToString function in Material UI's sx property doesn't seem to have

Every time I apply sx to a component that is rendered as a string and then displayed using dangerouslySetInnerHtml, the styles within the sx prop do not work.

Here is an example showcasing the issue:

Codesandbox: https://codesandbox.io/p/sandbox/wonderful-engelbart-xv9j2l?file=%2Fsrc%2FDemo.js%3A26%2C1

import * as React from "react";
import { renderToString } from "react-dom/server";
import Box from "@mui/material/Box";

function BoxExample({ color }) {
  return (
    <Box
      sx={{
        bgcolor: color,
      }}
    >
      <p>Content</p>
    </Box>
  );
}

export default function BasicButtons() {
  const badHtml = renderToString(<BoxExample color={"#01FF00"} />);
  return (
    <>
      <div dangerouslySetInnerHTML={{ __html: badHtml }} />
      <BoxExample color={"#00B2FF"} />
      {/* <BoxExample color={"#01FF00"} /> */}
    </>
  );
}

If you uncomment the third BoxExample and refresh, both green boxes will have their background color applied.

Answer №1

While experimenting with your sandbox, it seems that the CSS needed for the renderToString component is either not being generated or not being injected into the DOM. When uncommenting the third Box element, it triggers the generation and/or injection of the CSS, allowing the renderAsString component to finally access the necessary styles.

It's worth noting that both renderToString() and dangerouslySetInnerHtml are strongly advising against their usage. These methods bypass the full React rendering pipeline, leading to lackluster results and missing key elements that would typically be present if the code had been fully rendered by React.

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

How can I ensure that the scripts returned in HTML via AJAX are executed when using $.load()?

I have been trying to make an AJAX call and receive a partialView which contains some script that needs to be executed. I did some research and learned about the "eval" method, but then discovered that the $.load() method should handle this for me. Howeve ...

Implementing styling for an active link in NextJS that changes dynamically

I have a variety of categories with different products in each one. To handle this, I've created individual files in my pages folder named [...slug].js for each unique URL; For example, here are some of the URLs: /phones /laptops /tv I would like t ...

Styles and CSS have been successfully loaded, however, the content is not appearing

After attempting to import a web HTML CSS template into my self-made MVC, I encountered an issue. While the template works properly on its own, it fails to connect to the CSS files and display proper styles when accessed through my controller. Instead, onl ...

The 'innerHTML' property is not present in the 'EventTarget' type

Currently, I am working with React and Typescript. My goal is to store an address in the localStorage whenever a user clicks on any of the available addresses displayed as text within p elements. <div className="lookup-result-container& ...

Solution for dealing with error 'Cannot find Property length on type {} in React using TypeScript

Any ideas on how to fix the error "Property 'length' does not exist on type '{}'"? Below is the code snippet causing the issue: //component const SearchResults = ({ results }: { results: {} }) => { let pageCount = results? ...

Exploring ways to modify the color of a Button component from material-ui upon navigation interactions?

In my react application with material-ui, I am using the Button component. <Button classes={{root: classes.button, label: classes.label}} variant="raised" color="primary"> Which attribute should I change to alter the background color of the button ...

I created an image that can be clicked on, but unfortunately it only functions properly on the

I am currently working on creating an image that can be clicked to cycle through different images all within the same frame. While I have managed to get it to work, I am facing a limitation where it only responds to one click. count = 1; function myF ...

Using various functions for event listeners

Avoiding jQuery Hello there! I'm currently working on implementing multiple Event Listeners for a button. function logoContame(){ var logo = document.getElementById("logoheader"); logo.addEventListener("click", hideDivHistorias) ...

What could be causing all the flickering in this presentation?

Check out the jQuery slideshow I uploaded on my blog at robertmarkbramprogrammer.blogspot.com/2010/09/jquery-slideshow.html The slideshow is flickering in Chrome but looks fine in IE, Firefox, and even the standalone version. You can view it here: Here i ...

How can I select elements in CSS that are "between x and y"?

If I have an HTML table with 20 rows and 3 columns (20x3), I am looking to highlight the rows from 7 to 12 in red. What CSS selector should I use for this specific task? How can I define the range of rows to be styled as "between"? ...

"Alert: Cautionary notification when utilizing server action in the latest version of Next.js

I keep receiving this warning message in my server-side console while using server actions: Warning: Cannot specify an encType or method for a form that specifies a function as the action. React provides those automatically and they will be overridden. Ho ...

What is preventing Protractor from detecting Angular on a site that has been automatically initialized with Angular?

Whenever I try to utilize browser.get() in my code, I encounter the following error: Error: Angular could not be found on the page http://localhost:5000/#/login debug=timing&saveLogs=true&displayAll=true : angular never provided resumeBootstrap A ...

Creation of Components in React

Currently immersed in the world of react.js, I have been delving deep into its intricacies. One question that frequently crops up is about the usage of constructor. When exactly should it be used, similar to the snippet below, and when can it be omitted? ...

Using AngularJS to dynamically load content into Owl Carousel 2

I'm having trouble loading the owl carousel in angularjs dynamic content. Here is the modified html code I am using: <div id="Galeria" owlcarousel class="youplay-carousel gallery-popup"> <a class="angled-img" href="http://www.youtube. ...

React Helmet includes <script type="application/ld+json"> right after the closing </html> tag

After integrating a third-party widget on my website to display Rich Snippets stars, I encountered an issue where the ld+json markup was not being recognized by Google's bots and structured data testing tool. This was because the markup was placed out ...

Disable the default marker in Mapbox Geocoder

As a newcomer in the world of ReactJS and Mapbox GL JS, I am working on a project where I have successfully integrated a map with Geocoder, Navigation Controls, and Markers based on locations from a JSON file. However, I encountered an issue - whenever I s ...

Clicking on Bootstrap Select Does Not Trigger Dropdown Opening

Currently, I am working on generating a dynamic set of bootstrap-select widgets that include a dropdown. My main challenge lies in preventing the select from closing the dropdown, which requires me to use 'event.stopPropagation()' on the dropdown ...

Here's a simple script to display a div or popup only once in the browser using plain vanilla JavaScript

// JavaScript Document I'm attempting to make a popup appear in the browser only once. I believe using local storage is the key, but all I can find are solutions involving jQuery. I really want to achieve this using plain JavaScript without relying ...

Importance of value attribute in <input ng-model ..>

Maybe a silly inquiry, but I'm curious about the purpose of having value="" in this particular situation: <input ng-model="something.name" value="" class="input-xlarge" /> Are there any alternatives to keeping the value attribute empty? I init ...

Retrieve data from two databases and display the information from two separate arrays on a single ejs page after making two separate database calls

Currently, I am faced with a challenge where I need to render a page by passing two arrays that are populated by two separate database calls. It seems that when I only pass one array to the ejs page, everything works as expected. For a single array, my a ...