What's the best way to update the fill color of an SVG dynamically?

Is it possible to change the color of an SVG image dynamically without using inline SVG tags? I want to create a code that allows users to specify the source for the SVG tag and a hexadecimal color value, enabling them to customize any SVG image with their preferred colors.

The idea is to have a component where users can input the SVG source and color, and the code will automatically adjust the fill colors of the SVG based on these parameters. Any ideas on how to achieve this would be greatly appreciated. Thank you!

Here is an example of how the user interaction might look:

import Frame from './Frame.svg';
...
<Icon src={Frame} color='purple' />

This is my suggested UI component code:

import React from 'react';
import styled from 'styled-components';

const Icon = ({ src, color }) => {
  const StyledSVGIcon = styled(src)`
    width: 67px;
    height: 72px; 
    fill: ${color};
  `;
  return <StyledSVGIcon />
};

Sample content of Frame.svg file:

<svg width="73" height="71" viewBox="0 0 73 71" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0)">
<path d="M47.0139 71H40.8997C39.8807 71 39.541 70.332 39.541 69.664V63.6518C39.541 63.3178 39.8807 62.6498 39.8807 62.3157L64.3376 38.267C65.0169 37.599 65.6963 37.599 66.3756 38.267L72.4898 44.2792C73.1692 44.9472 73.1692 45.6152 72.4898 46.2833L48.033 70.332C47.6933 70.666 47.0139 71 47.0139 71ZM42.2584 67.9939H46.3346L69.0931 45.6152L65.0169 41.6071L42.2584 63.9858V67.9939Z" fill="#4B286D"/>
...
</g>
<defs>
<clipPath id="clip0">
<rect width="73" height="71" fill="white"/>
</clipPath>
</defs>
</svg>

Answer №1

Here is a demonstration of how to apply a color to an SVG element:

import React, { useState } from "react";
import styled from "styled-components";

export default function App() {
  const [selectedColor, setSelectedColor] = useState("blue");

  return (
    <div>
      <h1>Greetings from Stack Overflow!</h1>
      <StyledSVG 
        color={selectedColor} 
        src={'https://example.com/svg_image'}
        />
    </div>
  );
}

const StyledSVG = styled.svg`
  width: 500px;
  height: 500px;
  background-color: ${(props) => props.color};
  background-image: url(${(props) => props.src});
`;

The default color is blue, but you can customize it with RGB or hex values using sliders for the styled <svg />.

CodeSandbox: https://codesandbox.io/s/stack-63910588-pass-color-to-svg-birthday-card-ievg7?file=/src/App.js


The original poster mentioned they wanted to modify the children's color. You can achieve this by:

import React, { useState } from "react";
import styled from "styled-components";

export default function App() {
  const [chosenColor, setChosenColor] = useState("purple");

  return (
    <Container>
      <StyledSVG color={chosenColor} width="73" height="71" viewBox="0 0 73 71">
        <Frame />
      </StyledSVG>
    </Container>
  );
}

const Frame = () => {

  // This logic could be moved to a separate file.

  return (
  <>
  <g clip-path="url(#clip0)">
  <path d="M47.0139 71H40.8997C39.8807 71 39.541 70.332 39.541 69.664V63.6518C39.541 63.3178 39.8807 62.6498 39.8807 62.3157L64.3376 38.267C65.0169 37.599 65.6963 37.599 66.3756 38.267L72.4898 44.2792C73.1692 44.9472 73.1692 45.6152 72.4898 46.2833L48.033 70.332C47.6933 70.666 47.0139 71 47.0139 71ZM42.2584 67.9939H46.334…
  </g>
  <defs>
  <clipPath id="clip0">
  <rect width="73" height="71" fill="white"/>
  </clipPath>
  </defs>
  </>
  );
  
};

const Container = styled.div`
  height: 500px;
  width: 100%;

  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;

`;

const StyledSVG = styled.svg`
  & path {
    fill: ${props => props.color};
  }
`;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to create a stunning Bootstrap Jumbotron with a blurred background that doesn't affect the

I need help making my Jumbotron image blurry without affecting the text inside it! Below is the code from my index.html and style.css files. Any assistance would be greatly appreciated. body { background-image: url(bg1.png); background-repeat: repea ...

What is the best way to incorporate this code snippet into an object's value?

Is there a way to merge the headStyles object into the headText object? I have already injected the headStyles object into headConfig. import { makeStyles } from '@material-ui/core' const headStyles = { backgroundColor:'green', ...

Using PHP/JavaScript to activate a button once the timer reaches 00:00

I came across a JavaScript fiddle code that is working perfectly. Here it is: HTML <div id="worked">00:05</div> JS $(document).ready(function (e) { var $worked = $("#worked"); function update() { var myTime = $worked.h ...

TypeScript version 3.7 has implemented a new feature where it will now display errors for each individual invalid prop instead of grouping them together as it

Scenario using TypeScript 3.5.3 https://i.stack.imgur.com/wykd6.png link to interactive playground - TS 3.5.3 demo running successfully Example with TypeScript 3.7.2 https://i.stack.imgur.com/BPckB.png link to demo - TS 3.7.2 demo not functioning correctl ...

Making a list of members from an array of objects

Let's say I have a collection of items structured like this: var itemList = [ { date: '22/9/2016', status: 1, id: '11111' }, { date: '23/9/2016', status: 1, id: '22222' }, { date: '24/9/2016&ap ...

Accessing and showcasing MySQL information using hidden forms

I'm facing an issue with displaying the selected data from MYsql. The values are stored in my database fields, and I want the review of the chosen movie to show up when the user clicks the submit button, but it's not working as expected. Below i ...

What causes the HTML element's X position value to double when its X position is updated after the drag release event in Angular's CDK drag-drop feature?

I am facing a challenge with an HTML element that has dual roles: Automatically moving to the positive x-level whenever an Obsarbalve emits a new value. Moving manually to both positive and negative x-levels by dragging and dropping it. The manual drag a ...

Struggling with the development of a crossfading image gallery using jQuery's .animate() function while ensuring compatibility with IE8

Seeking assistance in creating a crossfading image gallery using jQuery and the .animate() function. I'm struggling to solve the issue of smooth fadeIn for the next image while maintaining compatibility with IE8. https://jsfiddle.net/Vimpil/fqhc1e9m/ ...

Here's a new take on the topic: "Implementing image change functionality for a specific div in Angular 8 using data from a loop"

I need to create a list with dynamic data using a loop. When I click on any item in the list, I want the image associated with that item to change to a second image (dummyimage.com/300.png/09f/fff) to indicate it's active. This change should persist e ...

How to retrieve the value of an element within a facebox div with jquery

On my page, I have two div tags displayed below. Whenever I try to retrieve the value of the itemName element using $('#itemName').val();, it always returns the value of the element in the first div (which is blank). Is there a way to access the ...

What is the process for generating an array of arrays in a React component?

I'm currently working on developing a word-guessing game similar to Wordle using React. The interesting twist in this game is that players have the ability to choose both the number of attempts allowed and the length of the word they are trying to gue ...

Passing the AngularJS ng-model from a template to a directive's controller

I have created a directive with a controller that is responsible for building a form to post comments to an API through CommentsService Here is a snippet of how my directive looks: app.directive('appComments', function( CommentService ) { r ...

Incorporate child routes within a React component

I've been attempting to include <route> in a component within a routers component, but it doesn't seem to be working. Can anyone provide some assistance? My login page currently has a form and I'd like to switch that out with routes. ...

Experience real-time updates for CSS gradients

It may seem minor, but I am looking for a solution if possible. I have a webpage where I want to implement a CSS gradient as the background. The page has a fixed header at the top with content scrolling behind it, and I want the background gradient to cont ...

Creating an animated full-width SVG with a background image

This has been quite a challenge for me. I have successfully implemented the main functionality that I wanted in this codepen. The SVG is divided into 3 sections, with the middle section sliding away from the others when you click the "Find Out More" button ...

Using Database Data in a Material UI Select Component

I'm having trouble populating a select component from Material UI with data retrieved from my database. Although I can display the data in the component, upon selecting an option it breaks and displays the error "categorias.map is not a function". Any ...

Sorry, but you can only use one 'in' filter in your query

this.ref.collection("users", ref => ref.where("uid1","in", [reciverId, senderId]) .where("uid2","in", [reciverId, senderId])) throws an error stating: "Invalid query. Multiple 'in' filters cannot be used." ...

Is it possible to consolidate React and React-DOM into a unified library instead of having them separate?

Is it possible to combine React.JS and React-DOM.JS into a single library? In all the web applications I've encountered, we always have to import both libraries separately. Have there been any cases where either of these libraries can be used on its ...

ReactJS - Troubleshooting the unresponsive modal issue on initial click

On the initial click, the modal does not seem to be working. It only functions properly from the second attempt onwards. Does anyone have a solution for this issue? Thank you Note: No need to worry about the messy jQuery append part; I will clean it up la ...

Is it possible to modify the number format of an input field while in Antd's table-row-edit mode?

I am currently utilizing the Table Component of Ant Design v2.x and unfortunately, I cannot conduct an upgrade. My concern lies with the inconsistent formatting of numbers in row-edit mode. In Display mode, I have German formatting (which is desired), but ...