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

Angular 4 Operator for adding elements to the front of an array and returning the updated array

I am searching for a solution in TypeScript that adds an element to the beginning of an array and returns the updated array. I am working with Angular and Redux, trying to write a reducer function that requires this specific functionality. Using unshift ...

Upgrade the WordPress light editor to the advanced version

After developing a script to upgrade the WordPress editor on a specific page from light mode to Advanced once a user clicks the Unlock button and confirms their desire to make the switch, an issue arose. Despite deducting 5 coins from the user's balan ...

Integrate an external script with React and initialize a new instance

I've been working on integrating a neat canvas background feature from this GitHub project into my React web application. Here's what I've attempted: import {WarpSpeed} from './warpspeed.js' import WarpSpeed from './warpspee ...

Enhance the spacing between the UL-LI navigation menu and the currently selected item

I'm struggling with adjusting the spacing between items in my navigation menu, specifically the li elements that are currently too close together. I've attempted to increase the margin-left within the .main_menu li CSS rule, but it doesn't s ...

What is the best method for enclosing all text within an HTML document with a different element?

For example: FROM <div> whats up! <div> whats up2! </div> thank you for your help <div></div> </div> TO <div> <span>whats up!</span> <div><span> whats up2! </span&g ...

To ensure a successful redirection process without information loss, it is essential to address any potential issues with data input into

How can I properly implement a page redirection? Below are the relevant code snippets. <link rel="stylesheet" type="text/css" href="payout.css"/> <font face='calibri'> <?php session_start(); $conn = @mysql_connect("localho ...

"Utilizing social links in web design for a seamless user experience

I'm currently exploring ways to repair the design of social media links. The GitHub and Spotify icons are displaying at different sizes, and it seems like the Blogger icon is not aligning correctly: Referring to How To Create Social Media Buttons - ...

Executing getJSON requests in perfect synchronization of time

For my weather project, I have two JSON requests to make. The data from the first request is needed in order to personalize the second request for the user. The first request retrieves the latitude and longitude of the user, which are then required for the ...

Break free/Reenter a function within another function

Is there a way to handle validation errors in multiple task functions using TypeScript or JavaScript, and escape the main function if an error occurs? I am working in a node environment. const validate = () => { // Perform validation checks... // ...

PHP Instant Chat Improvements

I am in the process of developing a messaging system that consists of the following components: A form that allows users to send messages, with PHP handling the insertion of data into a MySQL Table named userMessages upon submission. A PHP page that ...

Is the risk of using deprecated synchronous calls on the main thread worth it in JavaScript?

I have created a single page web application that relies on modifying a section of the page and then calling specific functions to format this section after it has been modified. One of the crucial post-modification calls I need to make is MathJax. Howeve ...

Setting up server-side rendering (SSR) for a Rails 6 application using webpacker and React - a

It seems that with the inclusion of Webpacker in newly scaffolded Rails apps, using a gem like React Rails may not be the ideal choice. Is there a recommended approach to implementing server-side rendering (SSR) on a Rails app with React, or would I need ...

Invoke a functional component when a button is clicked in a React application

I have a functional component that includes a button. My goal is to trigger another functional component when this button is clicked. Upon clicking the Submit button, the Preview button appears. When the user clicks on the preview button, it should call t ...

Retrieve the current browser URL using getServerSideProps

When I call getServerSideProps, I am passing in the req and res parameters as follows: export async function getServerSideProps({ req, res }) {} I'm trying to retrieve the current browser URL path but it doesn't seem to be available in the reque ...

What could be causing the repeated calls to a computed function in vuejs?

In my Vuejs application, I start by fetching initial data and setting it in the store: const app = new Vue({ router, store, mounted: function() { var that = this; $.get("/initial_data/", {}, function(data) { that.$s ...

Having trouble extracting parameters from the router listen event in react-router?

Having trouble accessing the route parameter with react-router router.listen() method. It seems to fail, but I found a workaround using window.location.pathname.split('route/')[1]. Any suggestions? I've been investigating why this issue occ ...

Tips for avoiding parent div click interference in Angular

Working with Angular8, I have a div containing a routelink along with other components including a checkbox. Here's the structure: <div [routerLink]="['/somewhere', blablabla]"> <!--other components that navigate to the ro ...

Feeling lost when it comes to tackling the Data Access Object/Layer in an Express/MongoDB setup?

I currently have an Express application that is integrated with MongoDB. My goal is to decouple my database access from the server layer. However, in trying to achieve this, I've encountered two main approaches: Passing Res as an argument //server.j ...

Creating a customized component using unique styles in Material UI version 1

Currently, I am facing a challenge in styling my Card component with a width of 75 pixels while using Redux and Material UI V1. Despite following the example provided by Material UI on custom styling through withStyles and connect, I have not been able to ...

What is the best way to display all divs once more after all filter-checkboxes have been unchecked?

I created a custom filter that displays board games based on the number of players and playing time selected through checkboxes. Initially, the filter works as intended when first loaded and used. However, I encountered an issue where if all checkboxes are ...