Search code examples
reactjssvgbackground-imagedata-uri

React - Trying to pass SVG fill color as a prop while using svg as data in background image property?


I wish to dynamically change the fill color of a svg pattern that I'm using as a background image property in a container. I am doing this through using the data uri and directly injecting the SVG code as a value in a styled component. Currently it won't recognise the prop and the pattern just disappears. This works when I sue the fill color as a static value. Is it the way I wrote it?

Here some code -

import React, { useState } from "react";
import styled from "styled-components";
import './App.css';

const Container = styled.div`
   height: 50vh;
   width: 100%;
   background-color: ${props => props.bg};
   background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='${props => props.color}' width='8' height='8' viewBox='0 0 8 8'%3e%3cpath d='M5.25 0l-4 4 4 4 1.5-1.5L4.25 4l2.5-2.5L5.25 0z'/%3e%3c/svg%3e");
   background-size: cover;
`;


function App() {
   const [color, setColorChosen] = useState("green");
   const [bgChosen, setbgChosen] = useState("yellow");
   
  return (
     <>
         <Container bg={bgChosen} color={color}>
            
         </Container>
      </>
  );
}
export default App;

Solution

  • I am not sure why it's not working for you, it works for me. Are you using JS or TS? can I see the error message too?