1

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

Lana Hanna
  • 91
  • 1
  • 9
  • Following document will help you to resolve your issue: https://smartdevpreneur.com/styling-material-ui-before-after-hover-active/ – Akshay phalphale Sep 15 '22 at 09:39
  • @Akshayphalphale thank you for your response... I've checked the link and it's not related to the problem... I have no problem with styling pseudo Element ... my problem is how to add mui icon to that pseudo element content – Lana Hanna Sep 15 '22 at 10:59
  • Is it mandatory to use icons from `@mui/icons-material` package or is it ok if you use icons directly from [Material Icons](https://fonts.google.com/icons?icon.set=Material+Icons)? – Ahmet Emre Kilinc Sep 16 '22 at 20:08
  • @AhmetEmreKılınç with Material Icons I jsut add The code point to the content ,right? – Lana Hanna Sep 17 '22 at 07:30

1 Answers1

1

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.

Ahmet Emre Kilinc
  • 5,489
  • 12
  • 30
  • 42