← Back
css react

Background SVG images in React

import Background from "./Background";

I've done it before, but is the first time I use it in a React project:

background-image: url("data:image/svg+xml,%3Csvg width='8' height='8' viewBox='0 0 6 6' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='%23EBEBEA' fill-rule='evenodd'%3E%3Cpath d='M5 0h1L0 6V5zM6 5v1H5z'/%3E%3C/g%3E%3C/svg%3E");

Bear in mind that you have to escape characters, so #EFEFEF must be %23EFEFEF

Here's the code:

const IMAGE = `url("data:image/svg+xml,%3Csvg width='8' height='8' viewBox='0 0 6 6' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='%23EBEBEA' fill-rule='evenodd'%3E%3Cpath d='M5 0h1L0 6V5zM6 5v1H5z'/%3E%3C/g%3E%3C/svg%3E")`;

const Background: React.FC = () => (
<div style=></div>
);

You have to be care: you need to include parenthesis, but not the last semicolon ;

And here's the result: