Home > Back-end >  I not able set SVG as background image in react
I not able set SVG as background image in react

Time:08-05

I am trying to set svg as background image of my Container div. But something goes wrong. My SVG arrow function:-

const CurveOne = () => {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320">
      <path
        fill="#EEEEEE"
        fill-opacity="1"
        d="M0,192L48,165.3C96,139,192,85,288,69.3C384,53,480,75,576,90.7C672,107,768,117,864,128C960,139,1056,149,1152,128C1248,107,1344,53,1392,26.7L1440,0L1440,320L1392,320C1344,320,1248,320,1152,320C1056,320,960,320,864,320C768,320,672,320,576,320C480,320,384,320,288,320C192,320,96,320,48,320L0,320Z"
      ></path>
    </svg>
  );
};

export default CurveOne;

My Container styled div component:-

const Container = styled.div`
background-image: url(${CurveOne});
`;

CodePudding user response:

You can Import SVG as a component.

import { ReactComponent as CurveOne } from './CurveOne.svg';

const App = () => {
  return (
    <div className="App">
      <CurveOne />
    </div>
  );
}
export default App;

Follow this blog by LogRocket for info on SVG in React.

CodePudding user response:

In background-image: url(...) the url should be a string, but you passed a function CurveOne which will be coerced to a string and results in invalid style.

Instead, you can use a data-uri for the string. One tool for the conversion is available online: https://heyallan.github.io/svg-to-data-uri/

Or, if you want to use the function, you can refer to the svgToDataURI function from https://heyallan.github.io/svg-to-data-uri/js/svg-to-data-uri.js (I am not sure if I am allowed to copy the function in my answer) and then it can be used like the following:

let svgString = 
`
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320">
      <path
        fill="#EEEEEE"
        fill-opacity="1"
        d="M0,192L48,165.3C96,139,192,85,288,69.3C384,53,480,75,576,90.7C672,107,768,117,864,128C960,139,1056,149,1152,128C1248,107,1344,53,1392,26.7L1440,0L1440,320L1392,320C1344,320,1248,320,1152,320C1056,320,960,320,864,320C768,320,672,320,576,320C480,320,384,320,288,320C192,320,96,320,48,320L0,320Z"
      ></path>
    </svg>
`

let dataURI = svgToDataURI(svgString);

const Container = styled.div`
background-image: url(${dataURI})
`;
  • Related