Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading