Utilize Material UI SVG icons as background imagery

Is it possible to use svg images from @material-ui/icons as backgrounds for other elements? I attempted the code below without success.

import CarIcon from '@material-ui/icons/DriveEtaRounded';

const carIcon = <CarIcon />

function Cover(){
  return (
    <div
        className={classes.cover}
        style={{ backgroundImage: 'url('+ carIcon+')' }}
    />
  )
}

Answer №1

@material-ui/icons are React components that utilize SVG data enclosed within <svg> tags through a utility function when you inspect their source code. However, you can achieve a background-image effect by directly using them with some additional styling:

import CarIcon from '@material-ui/icons/DriveEtaRounded';

function Cover(){
  return (
    <div style={{position: 'relative', width: '200px', height: '100px'}}>
      <CarIcon style={{position: 'absolute', left: 0, top: 0, width: '100%', height: '100%'}} />
    </div>
  )
}

While this example demonstrates the concept, it is effective as long as the parent element's dimensions are defined by other content. To mimic the behavior of background-size: cover, you can include

preserveAspectRatio='xMidYMid slice'
within the icon component (the default value is equivalent to contain). One advantage of this method is that the icons retain their SVG nature, allowing for further customization and animation possibilities.

Answer №2

Referring to a snippet from the MUI documentation on custom switches, you have the option to assign the backgroundImage property to an Mui icon by adhering to the prescribed structure:

backgroundImage: `url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" height="20" width="20" viewBox="0 0 20 20">
  <path fill="${encodeURIComponent('#fff',)}" 
  d="M4.2 2.5l-.7 1.8-1.8.7 1.8.7.7 1.8.6-1.8L6.7 5l-1.9-.7-.6-1.8zm15 8.3a6.7 6.7 0 11-6.6-6.6 5.8 5.8 0 006.6 6.6z"/>
</svg>')`,

The process may seem convoluted due to the requirement for the precise svg path (the 'd' attribute in the aforementioned example). To ascertain the 'd' value for the svg you wish to utilize, you can locate the icon's file within node modules (e.g node_modules > @mui > icons-material > DriveEtaRounded.js):

DriveEtaRound.js:

"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));

var _jsxRuntime = require("react/jsx-runtime");

var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
//
// ----  d value here \/
// 
  d: "M18.92 5.01C18.72 4.42 18.16 4 17.5 4h-11c-.66 0-1.21.42-1.42 1.01l-1.97 5.67c-.07.21-.11.43-.11.66v7.16c0 .83.67 1.5 1.5 1.5S6 19.33 6 18.5V18h12v.5c0 .82.67 1.5 1.5 1.5.82 0 1.5-.67 1.5-1.5v-7.16c0-.22-.04-.45-.11-.66l-1.97-5.67zM6.5 15c-.83 0-1.5-.67-1.5-1.5S5.67 12 6.5 12s1.5.67 1.5 1.5S7.33 15 6.5 15zm11 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM5 10l1.27-3.82c.14-.4.52-.68.95-.68h9.56c.43 0 .81.28.95.68L19 10H5z"
//
// ----  d value here /\
// 
}), 'DriveEtaRounded');

exports.default = _default;

Your final outcome should resemble:

backgroundImage: `url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" height="20" width="20" viewBox="0 0 20 20">
  <path fill="${encodeURIComponent('#fff',)}" 
  d="M18.92 5.01C18.72 4.42 18.16 4 17.5 4h-11c-.66 0-1.21.42-1.42 1.01l-1.97 5.67c-.07.21-.11.43-.11.66v7.16c0 .83.67 1.5 1.5 1.5S6 19.33 6 18.5V18h12v.5c0 .82.67 1.5 1.5 1.5.82 0 1.5-.67 1.5-1.5v-7.16c0-.22-.04-.45-.11-.66l-1.97-5.67zM6.5 15c-.83 0-1.5-.67-1.5-1.5S5.67 12 6.5 12s1.5.67 1.5 1.5S7.33 15 6.5 15zm11 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM5 10l1.27-3.82c.14-.4.52-.68.95-.68h9.56c.43 0 .81.28.95.68L19 10H5z"/>
</svg>')`,

Be cautious to use 'd="... and not d:"...

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

How can I specify a CSS class pair within a CSS module in React?

<NavLink to={rootPath + path} activeClassName="active" className={scss.navlink} > <ListItem button key={name}> <ListItemIcon> <Icon htmlColor="#E1F ...

Maximizing space efficiency in Bootstrap 5

Hello there I have a query; I am currently utilizing Bootstrap 5 for my website, and it's working well. However, I would like Bootstrap to fill the entire page instead of just 80%; (Refer to image) https://i.sstatic.net/Iswmu.jpg <head> ...

Updating the logo image on mobile devices using responsive CSS styling

My goal is to show a different image to users on mobile devices using only CSS, as I am unable to access the HTML code. On mobile, I used display:none for the header-logo-image img { and then added a background-url to the div to successfully display my alt ...

Get notified about the number of cells you've selected by simply dragging on a table

Is there a way to display the number of selected cells in a table when dragging with the mouse? I have a table set up, and I'd like to create an alert that shows how many cells are selected while dragging. Here is the link to my fiddle: http://jsfiddl ...

Move the data from the dynamic element to the React component

I have successfully implemented code that allows me to dynamically create a component with images and save the state. The state management is handled through this array: const [UploadLogos, setUploadLogos] = useState([0]); const dynamicLogos = (id, url) = ...

A slender gap of white space delicately separates the transformed parent from its offspring

When trying to align a parent div with a child div that has the same background-color as the parent's border-color, I am encountering an issue. Despite my efforts, there seems to be a thin line of whitespace separating the two divs. It is worth notin ...

Preventing the text field from being clickable in Material-UI when it is set to read-only

I'm dealing with a material-ui text field that's set to read-only mode, but it still highlights when clicked on. Is there a way to disable clicking while in read-only mode? ...

Using the attribute data-ng-repeat along with the <option> tag allows for dynamic iteration and

Hello there, I am a beginner with AngularJS and I am struggling to understand how to create my <option> list. I would like my output to resemble the example in this fiddle: http://jsfiddle.net/XdpJv/ This is what my current code looks like: <se ...

Tips for displaying a loading message during an AJAX request?

My AJAX function is set up like this: function update_session(val) { var session_id_to_change=document.getElementById('select_path').value; $.ajax({ type: "GET", url: "/modify_path/", asy ...

Obtain the state of child components that are linked to Redux using enzyme

I am currently in the process of testing a redux connected component. This particular component experiences changes in its properties upon a resize event. My goal is to mount the DatePicker component using enzyme, trigger a resize event through dispatch, ...

Is there a way to remove deleted SASS styles from the generated CSS?

Is it possible to remove markups from a generated css file using sass? For instance, in my scss file I have: body{ background:$dark; } The resulting CSS file looks like this: body{ background: #000; } If I delete that line of code in sass, what will h ...

How do I retrieve the content within this HTML element using JavaScript based on its ID?

Is there a way to extract the string from this specific HTML element using JavaScript? The element has an id of recItemString_GPLA\|input, and within it, there is a string containing "qty" that I need to retrieve. Upon inspection of the element, the f ...

Tips for enhancing the contents of a single card within a react-bootstrap accordion

Currently, I am facing an issue with my columns expanding all cards at once when utilizing react-bootstrap accordion. My goal is to have each card expand individually upon clicking on its respective link. However, I am encountering difficulties in implem ...

Tips for transmitting dropdown selections to a different PHP form using jQuery

After spending a considerable amount of time searching for answers online, I realized that I need some help. Despite finding helpful articles and resources on jQuery, I am still struggling to understand certain concepts. As a beginner in this field, I am w ...

Determine the cumulative quantity of items in the shopping cart using React

I am struggling to obtain the total number of items in my cart. The issue is that it only counts the unique items in the cart. If there are duplicates, such as two of the same item, they are not included in the Total Items count. Here is a CodeSandBox dem ...

Mastering the art of transitioning between DIV elements

I am looking to implement a rotating three-card display on click, and have come up with the following code: $('.box1').click(function(){ $('.box1').toggleClass('removeanimate'); $(this).toggleClass('go'); ...

applying conditional rendering in vue.js

I'm currently working on developing a chat application using the guidelines outlined in this tutorial: https://socket.io/get-started/private-messaging-part-1/ One of my goals is to customize the appearance of the messages, so that when a message is s ...

Increase the size of the image beyond the boundaries of its container

I am facing an issue with an image inside a div. Whenever I add a margin-top, the background of the div extends downwards, which is not the desired behavior. How can I fix this problem? Below is my code snippet: <div id="content"> <div class=" ...

Small web app encounters error 501, indicating not implemented functionality

I've been working on uploading images to an S3 bucket using react and expressjs. However, whenever I try to upload the image, I keep getting a 501 Not Implemented Error. My approach involves using axios to communicate with the endpoint created in the ...

Removing CSS from a Link in react-router-dom

My attempt to create unique divs for different pages using the code in my home.js didn't go as planned. <Link to="Subject1"> <Product title="The Lean Startup" image="https://images-na.ssl-images-amazon.co ...