React SVG component as background-image to div

React SVG component as background-image to div

svg as background-image
react background image
styled-components background image
css background image
reactstrap background image
react-svg-loader
svg background-image div
react svg from url

I am trying to get styled-components to take an SVG that is a react component and set it as a background-image but I get the error:

TypeError: Cannot convert a Symbol value to a string

SVG component code:

import React from "react";

const testSVG = props => {
  return (
    <svg version="1.1" id="Layer_1" x="0px" y="0px" viewBox="0 0 193.3 129.7">
      <g>
        <g>
          <g>
            <path
              fill="#434343"
              class="st0"
              d="M162.4,116c-4.6,7.5-15.6,13.6-24.4,13.6H16c-8.8,0-12.3-6.2-7.7-13.7c0,0,4.6-7.7,11.1-18.4
                c4.4-7.4,8.9-14.7,13.3-22.1c1.1-1.8,6.1-7.7,6.1-10.1c0-7.3-15-24.9-18.5-30.7C13.5,23.6,8.3,14.9,8.3,14.9
                C3.7,7.4,7.2,1.2,16,1.2c0,0,65.9,0,106.8,0c10,0,25.9-4.5,33.5,3.8c8.7,9.3,15.5,25.4,22.5,36.8c2.6,4.2,14.5,18.3,14.5,23.8
                c-0.1,7.6-16,26.1-19.6,32C167.1,108.3,162.4,116,162.4,116z"
            />
          </g>
        </g>
      </g>
    </svg>
  );
};

export default testSVG;

Container component code:

import React, { Component } from "react";
import StepSVG from "../../components/UI/SVGs/Test";

class StepBar extends Component {
  render() {
    const { steps } = this.props;

    return (
      <div>
        {steps
          ? steps.map(step => {
              return (
                <Wrap key={step._id} bg={StepSVG}>
                  <P>
                    {" "}
                    <Link to={"/step/" + step._id}>{step.title} </Link>
                  </P>
                </Wrap>
              );
            })
          : null}
      </div>
    );
  }
}

export default StepBar;

const Wrap = styled.div`
  padding: 30px 30px 0 0;
  display: inline-block;
  background-image: url(${props => props.bg});
`;

I am using create-react-app out of the box.

I also tried without using styled components and used inline styles in place to no success.

Is it possible to use an SVG as a background-image in this context with the SVG being a component?


Unfortunately, what you're trying to achieve is not possible. You'll have to keep your SVG as an actual .svg file (and link to that), or do some CSS trickery to place SVG component behind your foreground-component.

In other words:

<!-- step.svg -->
<svg version="1.1" id="Layer_1" x="0px" y="0px" viewBox="0 0 193.3 129.7">
  <!-- copy paste your svg here -->
</svg>

And in your component:

import stepSvgUrl from "../../components/UI/SVGs/step.
// ...
<Wrap key={step._id} bg={stepSvgUrl}>

When you import an SVG file like that, create-react-app applies a Webpack loader that includes the generated URL to the SVG you're importing - which is fine to pass into the background-image css property.

Hope this helps!

How to use React SVG Patterns as Backgrounds, By using SVG, I avoided to use other image formats which would add it would be possible to wrap the Logo component in a <div /> container with CSS to align the SVG pattern as a reusable React background component. In this post we are going to learn about how to use svg in React. Scalable Vector Graphics (SVG) are the most popular image format for getting excellent image quality in any resolution. What is Svg ? SVG or Scalable Vector Graphics are XML-based image formats that can be scaled to any size while maintaining the quality of the image.


For React SVG background images, I find this works best:

// MyComponent.js

import mySvg from './mySvg.svg';

...

function MyComponent() {
  return (
    <div
       className="someClassName"
       style={{ backgroundImage: `url(${mySvg})` }}
    > 

... etc

The path to the SVG file will change when webpack bundles, so by using the template string you can keep things linked up.

In the CSS class you can do whatever styling you like.

Rendering SVGs as images directly in React - Ian Sinnott, Here's the gist of it—if you have some raw stringified SVG then you can use it as a data URI: .some-div { background: url("data:image/svg+xml  In this tutorial, we are going to learn about how to set a background-image in the react app using inline styles and external css. This tutorial assumes that you already created a new react project using create-react-app.


Actually, there is a way to achieve what you want, without the SVG beeing a component:

Here is the updated StepBar component:

import React, { Component } from "react";
import StepSVG from "../../components/UI/SVGs/test.svg";
import encodeSVG from '../../lib/encodeSVG';

class StepBar extends Component {
  render() {
    const { steps } = this.props;

    return (
      <div>
        {steps
          ? steps.map(step => {
              return (
                <Wrap key={step._id} bg={StepSVG}>
                  <P>
                    {" "}
                    <Link to={"/step/" + step._id}>{step.title} </Link>
                  </P>
                </Wrap>
              );
            })
          : null}
      </div>
    );
  }
}

export default StepBar;

const Wrap = styled.div`
  padding: 30px 30px 0 0;
  display: inline-block;
  background-image: ${encodeSVG(bg, '#FF9900')};
`;

Here is encodeSVG lib file:

var symbols = /[\r\n"%#()<>?\[\\\]^`{|}]/g;

function addNameSpace(data) {
  if (data.indexOf('http://www.w3.org/2000/svg') < 0) {
    data = data.replace(/<svg/g, "<svg xmlns='http://www.w3.org/2000/svg'");
  }

  return data;
}

function encodeSVG(data) {
  // Use single quotes instead of double to avoid encoding.
  if (data.indexOf('"') >= 0) {
    data = data.replace(/"/g, "'");
  }

  data = data.replace(/>\s{1,}</g, '><');
  data = data.replace(/\s{2,}/g, ' ');

  return data.replace(symbols, encodeURIComponent);
}

var encode = function(svg, fill) {
  if (fill) {
    svg = svg.replace(/<svg/g, `<svg fill="${fill}"`);
  }
  var namespaced = addNameSpace(svg);
  var dimensionsRemoved = namespaced
    .replace(/height="\w*" /g, '')
    .replace(/width="\w*" /g, '')
    .replace(/height='\w*' /g, '')
    .replace(/width='\w*' /g, '');
  var encoded = encodeSVG(dimensionsRemoved);

  var header = 'data:image/svg+xml,';
  var dataUrl = header + encoded;  

  return `url("${dataUrl}")`;
};

You import the svg, and use a string loader for svgs with your preferred build system (for example WebPack), pass that svg to encodeSVG, et voila! :)

06: Using SVG, SVG images can be used as background-image in CSS as well, just like PNG, JPG, or GIF. .element { background-image: url(/images/image.svg); } All the same​. Where does React come into all this? When using SVG in a web document, you have two options. Either render the SVG document as is, or use it as source in the img tag. The preferable option is to use it as is, since SVG in the image tag is rendered as an image and cannot be manipulated beyond the css styles for the image tag.


url(`data:image/svg+xml;utf8,${svgTxt}`)

;or

url(`data:image/svg+xml;base64,${btoa(svgTxt)}`)

that's it.

How to get CSS background images with styled-components , img/bg.gif); width: 2000px; height: 2000px; ` Thanks in advance! How i made this with CSS style in react ? :s const Content = styled.div` background-image: url(${props => props.img}); `;. <Content img={ImagePath} />  The swapping in occurs outside of React flow, so we don't want React updates to conflict with the DOM nodes @tanem/svg-injector is managing. Example output, assuming a div wrapper: < div > <!--


I ended up using user11011301's solution in combination with raw-loader to load the SVG content. Not the cleanest solution I'm sure, but I couldn't get it to work with other webpack loaders.

import searchIcon from '../../images/search.svg';

<input style={{backgroundImage: `url(data:image/svg+xml;base64,${btoa(searchIcon)})`}}/>

Simple Responsive Images With CSS Background Images , How do I make a background image fit in a div? The ReactComponent import name is significant and tells Create React App that you want a React component that renders an SVG, rather than its filename. Tip: The imported SVG React Component accepts a title prop along with other props that a svg element accepts. Use this prop to add an accessible title to your svg component.


How to use SVGs in React, How to use an SVG in a React app, slightly depends on the rest of your work if you want to use SVGs as background-image or content in CSS. or with an SVG <animate> element, this animation will run however the SVG  React is one of today’s most popular ways to create a component-based UI. It helps to organize an application into small, human-digestible chunks. With its “re-render the whole world” approach, you can **avoid any complex internal interactions between small components**, while your application continues to be blazingly fast due to the DOM-diffing that React does under the hood (i.e


How to set a Background Image in React, SVG is a vector graphics image format based on XML. so this means it can be navigated like a DOM element and also styled, although some  As you can see, styled-components lets you write actual CSS in your JavaScript. This means you can use all the features of CSS you use and love, including (but by far not limited to) media queries, all pseudo-selectors, nesting, etc.


How to use SVGs in React, With webpack, using static assets like images and fonts works similarly to CSS. background-image: url(. Tip: The imported SVG React Component accepts a title prop along with other props that a svg element accepts. I was really excited to attend, partially because I had so many questions about SVG and React. There are a lot of bits about working with React and SVG, and especially manipulating it, that aren’t quite supported yet. One of the major gaps for me was the <use> element, as most SVG icon systems are built with <use>.