What is the method to alter the color of an SVG source within an image tag?

I am currently working on a component that involves changing the color of an SVG icon from black to white when a color prop is given.

export class CategoryIconComponent extends React.Component {

  static displayName = 'CategoryIcon';

  state = { icon: null };

  static propTypes = {
    title: PropTypes.string,
    color: PropTypes.string,
  };

  static defaultProps = {
    title: null,
    color: '#fff',
  };

  componentDidMount() {
    const { title } = this.props;

    if (getTopCategoryIcon('Concrete Contractors') != null){

      if(typeof getTopCategoryIcon('Concrete Contractors') === 'string'){
        this.setState({ icon: getTopCategoryIcon('Concrete Contractors') });
      }

      else{
        getTopCategoryIcon(title).then((newIcon) => {
          this.setState({ icon: newIcon });
        });
      }
    }
  }

  render() {
    const { icon } = this.state;
    const { color } = this.props;

    return (
      icon && (
        <TextIconContainer>

           // I am looking for a way to change the color of the icon from black to white using the color prop here
           // perhaps something like
          <img src={icon} width={25} height={25} color={color} />
        </TextIconContainer>
      )
    );
  }

Is there a CSS method that can achieve this, or any other approach to modify the color of the SVG component?

https://i.stack.imgur.com/DgWTp.jpg

Answer №1

I have found a unique way to implement SVGs in React by using them as simple components:

import React from 'react'

export const MySvg = ({ color }) => (
  <svg style={{ fill: color }}>
    ...
    ...
  </svg>
)

You can use this component in your code like so:

<MySvg color={color} />

This method is not a workaround or hack, but rather a creative solution. By utilizing this technique, you can achieve impressive theming and customization for your SVGs.

If you want to directly manipulate the fill attribute, you can easily extend the functionality of the component:

export const MySvg = ({ color }) => (
  <svg fill={color}>
    ...
    ...
  </svg>
)

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

Using JavaScript to transfer the data ID from a button to a form

I am working on a project where I have a button that triggers a modal: <button type="button" class="btn btn-primary add-subscription" data-toggle="modal" data-workspace_id="{{ workspace.id }}" data-target="# ...

Updating values of objects during iterations and for get requests is ineffective

Currently, I am looping through multiple select fields and attempting to run a get request for each of them. var selects = { key1 : value } $(".chosen-select-field").each( function ( index ) { selects[key2] = $( this ).attr('data-placeholder& ...

How can I retrieve data from the Hasura hook "useQuery"?

As a newcomer to web development, I am attempting a simple 'GET' request using the "useQuery" hook from Hasura. However, I am encountering difficulties accessing my data. Strangely, the query has been successfully tested on the Hasura console wit ...

The concept of undefined in JavaScript when an if condition is applied

In Node.js, there is a method used to handle API requests. An unusual behavior occurs when dealing with req.query.foo - even if it has a value defined, it becomes undefined when used in an if condition as shown below. Additionally, another req.query.foo ...

Why isn't my content appearing correctly on different pages?

This ecommerce site is my very first project using React. I have created pages for Contact, Login, and more. The footer and other components display correctly on the home page, but when navigating to other pages, the content appears shortened. For referen ...

Guidance on sending Ajax response to JavaScript function in OctoberCMS

In the HTML file of my component, I have created a form. When I submit the form, it triggers an AJAX call to an action defined in the component. Currently, my code is functioning properly and I am receiving a response. However, I now need this response to ...

Automatically omitting a selector that mimics a switch

After conducting thorough research, I discovered a variety of solutions using jQuery and Vanilla. While one answer perfectly addressed my issue, it failed to integrate effectively with the rest of my code. So, I decided to modify the code from this Stack O ...

Generating a matrix of HTML video elements in p5.js triggers Uncaught TypeError

Struggling to create a 2D array of video objects. It works fine with a regular array, but throws an error when attempting to make it 2D - Uncaught TypeError: Cannot read property 'tv' of undefined. The problem seems to be in this line of code: tv ...

Are you struggling with NodeJS asynchronous callback not achieving success?

Currently, I am working on developing a scraper that utilizes the async.map feature to iterate through an array, perform certain logic, and then map them to different values. async.map($('.listing tr').toArray(), GetLink, function(err, results) ...

moment.js incorrectly interprets the month as the day instead of the actual day

I am currently using moment.js (moment-with-locales.js - v.2.14.1) in my project. My goal is to extract only the date from a datetime string and remove the time. However, when I use the .format() method of moment.js, I receive an incorrect date. The datet ...

Combining two sets of elements in Java to form a Json using Jackson

Is there a way to combine two List of objects retrieved from the database into a single object in order to serialize with Jackson and deserialize in the view? ObjectMapper mapper = new ObjectMapper(); jsonTutorias = mapper.writeValueAsString(tuto ...

Toggle between list elements using the inner text of the elements with jQuery

My issue lies in figuring out why my filter function isn't properly working for toggling li elements. JavaScript: $("#searchbox1").on("keyup", function() { var value = $(this).val().toLowerCase(); $("#menulist li") ...

Utilizing Express.js: A Guide to Fetching File Downloads with a POST Method

Although GET requests are successful, I am facing challenges when using POST to achieve the same results. Below are the different code snippets I have attempted: 1. app.post("/download", function (req, res) { res.download("./path"); }); 2. app.post ...

Is it possible to set a unique identifier in Vue.js that persists even after the page is reloaded?

Currently, I'm working on a small project diving into Vue js - a Habittracker. Unfortunately, there is a bug in my code. When the page is reloaded and new habits are added, the function that should change the background doesn't work as expected. ...

Divide the string into several segments according to its position value

Here is a piece of text that I would like to divide into multiple sections, determined by the offset and length. If you have any questions or comments and would like to get in touch with ABC, please go to our customer support page. Below is a function ...

Issue with validation in react-hook-form when onBlur mode is activated

I have been attempting to show an error using yup and react-hook-form when the user selects more than 5 checkboxes, but I'm facing difficulties in achieving this. The issue arises when the seventh checkbox is selected instead of showing an error soon ...

What is the best way to integrate an asynchronously initialized API with a Vuex state?

As I delve into the world of Vue + Vuex, I find myself grappling with the challenge of initializing an API that relies on asynchronous methods. The common solutions I've attempted so far have hit roadblocks - can't use await outside an async fun ...

Extension for Chrome that enhances YouTube video playback experience

I'm struggling to figure out why this isn't functioning. I've reviewed the Google extension dev docs and examined some sample code. Checked various Stack Overflow questions and answers, but haven't received any helpful feedback or res ...

I'm wondering if there is a method for me to get only the count of input fields that have the class "Calctime" and are not empty when this function is executed

Currently, I am developing an airport application that aims to track the time it takes to travel between different airports. In this context, moving from one airport to another is referred to as a Sector, and the duration of time taken for this journey is ...

AngularJS allows for versatile filtering of objects and arrays using checkboxes

I am looking to implement a filter functionality similar to the fiddle mentioned in the first comment below. However, I do not want to capture the checkboxes category from ng-repeat. Instead, I only want to input the checkboxes' value and receive the ...