Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render React SVG component as backgroundImage

Tags:

reactjs

jsx

svg

I am trying to render a React Component that returns an <svg> as a backgroundImage of a <div>. Currently I am using ReactDOMServer with renderToStaticMarkup or renderToString but nothing shows up:

const SvgComponent = () => {
    return (
        <svg xmlns='http://www.w3.org/2000/svg'><rect fill='red' x='0' y='0' /></svg>
    )
}

const ParentComponent = () => {
    return (
        <div
            className={classes.banner}
            style={{
                backgroundImage: `url("data:image/svg+xml;utf8, ${ReactDOMServer.renderToStaticMarkup(<SvgComponent />)} ")`
            }}
        >
        </div>
    )
}

Would the package jsx-to-string the way to do it?

like image 779
oezguensi Avatar asked Oct 20 '25 01:10

oezguensi


1 Answers

You have to use encodeURIComponent() to URI encode the SVG data because React will not render the SVG data if it is not URI encoded. So,

const svgString = encodeURIComponent(renderToStaticMarkup(<SvgComponent />));

Also, set the width and height in <rect> of SVG like,

<rect fill="red" width={100} height={100} />

So final code should look like,

import ReactDOM from "react-dom";
import { renderToStaticMarkup } from "react-dom/server";
import React from "react";

const SvgComponent = () => {
  return (
    <svg xmlns="http://www.w3.org/2000/svg">
      <rect fill="red" width={100} height={100} />
    </svg>
  );
};



const ParentComponent = () => {
const svgString = encodeURIComponent(renderToStaticMarkup(<SvgComponent />));
  return (
      <div
          style={{
              backgroundImage: `url('data:image/svg+xml;utf8, ${svgString}')`,
             width:500,
             height:500
            }}
      >
      </div>
  )
}

ReactDOM.render(<ParentComponent />, document.getElementById("root"));

I have setup the same in CodeSandbox,

Edit React example

like image 135
Abhinav Kinagi Avatar answered Oct 26 '25 13:10

Abhinav Kinagi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!