Home > Net >  How do I add material icon for each rect in the svg
How do I add material icon for each rect in the svg

Time:12-30

I have a scenario where I am displaying the svg which has 5 rect and I want to add the delete icon (import DeleteIcon from '@mui/icons-material/Delete';) from material ui for each of the rect in front of the rect box, so total there should be 5 delete icon.

Material UI: https://mui.com/material-ui/material-icons/?query=delete&selected=Delete

Here is the code :

function svg() {
g.selectAll("g.legendCells")
.data(data)
.enter()
.append("g")
.append("rect")
g.selectAll("rect")
.attr("height", 1)
.attr("width", 1)
.style("fill", function (data) {
return data["color"];
});
g.selectAll("rect")
.attr("x", function (_d: number, i: number) {
return i;
})
.attr("y", 0);
}

Jsfiddle : https://jsfiddle.net/b2motr3c/2/

CodePudding user response:

How I would approach it is encapsulating each of the rects in group elements and placing a 'DeleteIcon' (from import) component inside it, take for instance:

<g>
  <rect x="70" y="10" width="20" height="20" style="fill: green" />
  <DeleteIcon />
</g>

Then adjust the x/y attributes and any other relevant properties to fit your desired look.

CodePudding user response:

The svg for the deleteIcon looks like this:

 <svg viewBox="0 0 24 24" data-testid="DeleteIcon">
    <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"></path>
  </svg>

You can put it inside the main svg element and transform it in a symbol with the same viewBox attribute. Since the symbol has a vieawBox the use element can take not only a x and y but also a width and height attributes.

As I've commented you can give the use the same x y width and height as the <rect>. This will position (x y) and resize (width, height) the symbol as you need.

Please observe that once you have a symbol you can reuse it (with <use>) as many times you need.

<svg width="300" height="200" style="outline: 5px dotted green">

  <symbol viewBox="0 0 24 24" id="DeleteIcon">
    <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"></path>
  </symbol>
  
  <rect x="70" y="10" width="20" height="20" style="fill:green" />
  
  <use href="#DeleteIcon" x="70" y="10" width="20" height="20" fill="white"/>

</svg>

  • Related