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

Is Jquery getting imported correctly, but AJAX is failing to work?

I am currently working on a Chrome extension that automatically logs in to the wifi network. I have implemented AJAX for the post request, but when I inspect the network activity of the popup, I do not see any POST requests being sent. Instead, it only sho ...

Angular does not select the variable_name within the $scope

Here is the HTML code I have written. <div class="container" ng-app="mintcart"> <div class="panel panel-default" ng-controller="categoriesctrl"> <input type="hidden" ng-model="session.sid" value="<?php echo session_id();?>"/&g ...

Why doesn't jQuery ajax work when sourcing the URL from a variable but works with a hard-coded URL?

During my experimentation with setting and getting the URL for a jQuery Ajax (post) call, I realized the value of dynamically setting the destination URL for the request. Here's how I attempted to achieve this: To set the URL to 'store.php' ...

Disabling the @import cache feature in LessCSS Assetic

I'm facing a minor issue that is robbing me of precious time. Currently, I am using the assetic plugin with the lesscss filter in my symfony2.1 project. The problem lies in Assetic not detecting changes in imported files when using the @import functi ...

Adding an iframe with inline script to my Next.js website: A step-by-step guide

For my Next.js project, I have this iframe that needs to be integrated: <iframe class="plot" aria-label="Map" id="datawrapper-chart-${id}" src="https://datawrapper.dwcdn.net/${id}/1/" style="width: ...

The image will come to life with animation as the background position is adjusted using Skrollr

Trying to create a div that switches the background image every X pixels scrolled. Initially experimented with changing the background-image, including using sprites and adjusting background position, but encountered a distracting "flickering" effect. Exa ...

Discovering the current time and start time of today in EST can be achieved by utilizing Moment.js

Need help with creating Start and End Time stamps using Moment.js in EST: Start Time should reflect the beginning of today End Time should show the current time. This is how I have implemented it using moment.js: var time = new Date(); var startTime=D ...

Tabindex issue arises due to a conflict between Alertify and Bootstrap 4 modal

When trying to call an Alertify Confirmation dialog within a running Bootstrap 4 Modal, I encountered an issue with the tab focus. It seems to be stuck in the last element and not working as expected. I suspect that this might have something to do with th ...

Additional GET request made after update request

After the user updates their contact information in the frontend application, the state is updated and a PUT API request is made to update the current information. When updating user contact details with a PUT call, should another GET call be made to retr ...

A step-by-step guide on how to display a specified amount of images in the center of

I'm currently working with a div that displays images dynamically loaded from a database, ranging from 1 to 5 images. The number of images may vary each time, and I need assistance in centering these images inside the div regardless of their quantity. ...

An issue has arisen in the production environment on AWS EC2 due to a problem with Nodemailer

When using nodemailer with node.js to send emails, I have set up the following configuration: var transporter = nodemailer.createTransport({ service: 'gmail', host: 'smtp.gmail.com', auth: { ...

Is Flex still wrapping elements even when set to nowrap?

My goal is to create a layout with 4 blocks, where the first section contains 2 blocks each occupying 50% of the width, followed by 2 other blocks in the next section. I am utilizing the flex property for this layout. I want the flex-container to take up ...

Sequelize Error: The WHERE parameter for 'email' is throwing an error due to an invalid value of 'undefined'

Currently, as part of my Node.js application, I am using Sequelize to develop a user registration feature. However, I seem to be facing an issue when attempting to verify the existence of a user based on their email address. The error that keeps popping up ...

What could be causing the partial to not load JavaScript properly?

Hello, I am a newcomer to Angular and I'm currently working on implementing the slick carousel. It functions properly on the index page, but when I try to use the same HTML in a partial and include it with ng-view, it doesn't work as expected. T ...

Establish the starting value for the material ui select component

One issue I'm facing is with a TextField in Material UI used as Select. While the MenuItems are functioning correctly in the form, I am struggling to pre-select an option based on data stored in a previously populated state. For instance, I have this ...

Ways to resolve issue with a build script that is missing when deploying Cypress in GitHub Actions

I recently attempted to implement a GitHub action to run Cypress tests on my app. Here is the configuration of my workflow file: name: Cypress Tests on: [push] jobs: cypress-run: runs-on: ubuntu-latest defaults: run: working-dire ...

What is the best way to modify multiple SVG fill colors in React?

Attempting to alter the color of two elements within an SVG in a React environment has presented some challenges. Converting the SVG into a component was successful, but changing the fills of both circles proved tricky due to the presence of multiple class ...

Lazy loading AngularJS UI router named views is an efficient way to improve performance

AngularJS UI router named views loading based on user access rather than loading at the time of state route access. Example: $stateProvider .state("login", { url: "/login", templateUrl: getTemplateUrl("login/Index") }) ...

Tips for updating state in response to changes in props

I am working on a project where I have a Parent component that renders a large form. The Parent component has child components Child1 - Child4, which are responsible for rendering input fields. Whenever the props of the Parent component change, I need to ...

Problem with Ajax functionality on Jquery Dialog

I have implemented a Jquery.dialog feature in my application for sending messages. When the user clicks on "new", the dialog box appears, allowing them to select the recipient (currently working with IDs instead of usernames). On the first opening of the ...