I'm trying to render a material-ui component inside renderToStaticMarkup (because I have to integrate with another library) but none of the css styles are applied:
import * as React from "react";
import ReactDOM from "react-dom/client";
import Button from "@mui/material/Button";
import { styled } from "@mui/material";
import { renderToStaticMarkup } from "react-dom/server";
const StyledButton = styled(Button)(() => ({
backgroundColor: "red"
}));
ReactDOM.createRoot(document.querySelector("#root")).render(
<React.StrictMode>
<div
dangerouslySetInnerHTML={{
__html: renderToStaticMarkup(<StyledButton>Test</StyledButton>)
}}
/>
</React.StrictMode>
);
https://codesandbox.io/s/heuristic-bouman-d1mogi?file=/index.js:0-527
I've encountered the same problem when upgrading from React 17 to React 18. I followed provided solution: https://beta.reactjs.org/reference/react-dom/server/renderToString#removing-rendertostring-from-the-client-code
Before my code was:
const iconHtml = renderToStaticMarkup(
<Box sx={{height: 50, display: "flex", justifyContent: "center", alignItems: "center"}}>
<LocationMarkerIcon color="primary" sx={{ position: "fixed", fontSize: 52 }} />
<PlaceIcon kind={kind} color={color} fontSize="small" sx={{ position: "fixed" }} />
</Box>
);
After change my code is:
const div = document.createElement('div');
const root = createRoot(div);
flushSync(() => {
root.render(
<Box sx={{height: 50, display: "flex", justifyContent: "center", alignItems: "center"}}>
<LocationMarkerIcon color="primary" sx={{ position: "fixed", fontSize: 52 }} />
<PlaceIcon kind={kind} color={color} fontSize="small" sx={{ position: "fixed" }} />
</Box>
);
});
const iconHtml = div.innerHTML;
div.remove();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With