How to add Mui Icon to the Content of pseudo elements (::after,::before) in React?

Viewed 31

I am trying to use mui Icons with pseudo Element "::before" with SX

here is my code:

import ArrowLeftIcon from "@mui/icons-material/ArrowLeft";

sx={{
                "&.Mui-selected::before": {
                  content: '"ArrowLeftIcon"',
                },

How to add ArrowLeftIcon to the content

1 Answers

Since content does not support HTML, you need to get the HTML content of the svg icon using ReactDOMServer.renderToStaticMarkup and then convert it to a data URL like this:

import ReactDOMServer :

import ReactDOMServer from "react-dom/server";

need a state variable for data URL:

const [muiIconContent, setMuiIconContent] = React.useState();

convert svg component to data URL:

useEffect(() => {
    const iconSvg = ReactDOMServer.renderToStaticMarkup(<ArrowLeftIcon />);
    const svgIconWithXlmns = iconSvg.replace(
      "<svg ",
      '<svg xmlns="http://www.w3.org/2000/svg" '
    );
    const resultUrl = "url('data:image/svg+xml," + svgIconWithXlmns + "')";
    setMuiIconContent(resultUrl);
}, []);

add data URL to style:

sx={{
     "&.Mui-selected::before": {
      content: muiIconContent,
      width: 30
    }
}}

You can take a look at this sandbox for a live working example of this approach.

Related