0

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 ?

RulerNature
  • 693
  • 4
  • 13
  • 40
  • It can not work, you are assigning a component as background. The output is something like this, "background-image": "url(
    Icon
    )".
    – Stefano Bucci Apr 13 '20 at 07:53

3 Answers3

2

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

  • yes but I don't know why is not really working, see example: https://codesandbox.io/s/hidden-framework-y4g11?file=/src/App.js – RulerNature Apr 13 '20 at 08:58
  • So ended up trying to use the libary and here is what I ended up with. https://codesandbox.io/s/wild-grass-sk9d9?file=/src/App.js By adding a className to the icon you can style it using CSS. – Andreas Steffensen Apr 13 '20 at 09:51
0

This cannot work because CSS rules cannot contain HTML code. By using the React component you are doing exactly that. The only way to specify a background image here is to use the standard way by specify the URL to an image in your CSS rule.

Mike Lischke
  • 48,925
  • 16
  • 119
  • 181
0

Create a Component to make reusable

import React from 'react';
import ReactDOMServer from 'react-dom/server';

const BackgroundIcon = ({ onClick = () => { }, children, className, Icon, backgroundImgSize = 124, top = 20, right = 20 }) => {
    const iconString = ReactDOMServer.renderToString(<Icon />);
    const encodedIcon = encodeURIComponent(iconString);
    const backgroundImage = `url("data:image/svg+xml;charset=UTF-8,${encodedIcon}")`;
return (
    <div
        onClick={onClick}
        style={{
            backgroundImage,
            backgroundSize: `${backgroundImgSize}px`,
            backgroundRepeat: 'no-repeat',
            backgroundPosition: `${top}% ${right}%`,
        }}
    >
        {children}
    </div>
    );
};

export default BackgroundIcon;

And use it like this

<BackgroundIcon
backgroundImgSize={124}
Icon={() => <AnIcon >}
strokeWidth={1.2} />}
top={98}
right={0}
> </BackgroundIcon>
RonCode
  • 1
  • 3