javascriptreactjsecmascript-6react-icons

React component as backgroundImage


I am using react-icons in my project and what this awesome package offer is to have all free fonts images in one place and served as react component.

what I am trying to achieve is to set a backgroundImage from component like:

<content className="content cover-content" style={{backgroundImage: `url(${<FaCar size={48} color="red"/>})`}}>

and I am not sure why this is not working, theoretically should work, any ideea ?


Solution

  • backgroundImage is a CSS property that needs a URL path to the image, you can download the icon and add it locally to your project.

    Or you could achieve the same result by using the CSS property z-index

    Using styled-components we can style the component by adding it behind the main content by using the CSS Property z-index.

     const Icon = styled.section`
          ..
          z-index: -1;
        `;
    

    We then add it around the Icon to style it as we want.

              <Icon>
                <FaCar />
              </Icon>
    

    Link to sandbox: https://codesandbox.io/s/wild-grass-sk9d9?file=/src/App.js