Enhancing SVG elements with CSS-Modules in ReactJS

I am developing an app using ReactJS and incorporating CSS-Modules for inline styles. Within my project, I have a separate svg file that contains an icon which I want to stylize in my component's css file.

Displayed below is the icon located at MyComponent/add.svg:

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Capa_1" x="0px" y="0px" viewBox="0 0 533.333 533.333" style="enable-background:new 0 0 533.333 533.333;" xml:space="preserve;">
<g>
    <path d="M516.667,200H333.333V16.667C333.333,7.462,325.871,0,316.667,0h-100C207.462,0,200,7.462,200,16.667V200H16.667   C7.462,200,0,207.462,0,216.667v100c0,9.204,7.462,16.666,16.667,16.666H200v183.334c0,9.204,7.462,16.666,16.667,16.666h100   c9.204,0,16.667-7.462,16.667-16.666V333.333h183.333c9.204,0,16.667-7.462,16.667-16.666v-100   C533.333,207.462,525.871,200,516.667,200z" />
</g>
</svg>

Here is the snippet from my MyComponent/MyComponent.css

.iconButton {

}

.icon {
  height: 50px;
  width: 50px;
  margin-left: 25px;
  margin-top: 25px;
  margin-right: 25px;
  margin-bottom: 5px;
}


.iconAdd {
  composes: icon;
  background: url('./add.svg');
}

Below is an excerpt from my MyComponent/MyComponent.jsx

import React, { Component } from 'react';
import styles from './MyComponent.css';

export default class MyComponent extends Component {
    render() {
        return (
            <div className={ styles.iconButton }>
                <div className={ styles.iconAdd }></div>
                <div>add</div>
            </div>
        );
    }
}

Although this setup is functioning properly, I encountered an issue when attempting to apply styles to the svg item (such as fill) without success.

If you have any recommendations on how to address this particular case, your input would be highly appreciated. Thank you for reviewing this question.

Answer №1

When working on my app, I encountered the need to manipulate SVG icons. Following the advice of @robjez, I decided to inline them first.

To achieve this, I created React components for each icon that required styling. Below is a snippet of one such component:

export default class FolderIcon extends Component {
    render() {
        return (
            <svg viewBox="0 0 475.082 475.082">
                <g>
                    <path d="M456.239,128.475c-12.56-12.562-27.597-18.842-45.11-18.842h-191.86v-9.136c0-17.511-6.283-32.548-18.843-45.107   c-12.562-12.562-27.6-18.846-45.111-18.846H63.953c-17.515,0-32.551,6.283-45.111,18.846C6.28,67.949,0,82.986,0,100.497v274.088   c0,17.508,6.28,32.545,18.842,45.104c12.562,12.565,27.6,18.849,45.111,18.849h347.175c17.514,0,32.551-6.283,45.11-18.849   c12.566-12.56,18.843-27.597,18.843-45.104V173.59C475.082,156.078,468.805,141.042,456.239,128.475z" />
                </g>
            </svg>
        );
    }
}

With the CSS Modules, I was able to easily stylize the SVG using code within the Component.

.icon svg {
    fill: #FFFFFF;
}

Here's how it can be used:

import FolderIcon from '../FolderIcon.jsx';
import styles from './Folder.css';

export default class Folder extends Component {
    render() {
        return <FolderIcon className={styles.icon} />;
    }
}

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

Sorting elements in order based on their attribute values using jQuery

Exploring the use of the data attribute with jQuery for the first time, I am attempting to reorder an element based on its data-order attribute. I am struggling to retrieve the correct value of the data-order attribute as it keeps returning 'undefine ...

What is the best way to incorporate data from a foreach method into a function call within an HTML string?

Having trouble calling a function with data from a foreach loop while generating HTML cards and buttons from an array. The issue seems to be in the renderProducts() method. /// <reference path="coin.ts" /> /// <reference path="prod ...

What's up with portable devices requiring two taps to hover over one DIV and affect another DIV?

Upon implementing "hover one DIV - affecting another inner DIV," a strange issue arose on iPad/iPhones where it now requires two taps to click on the link within the DIV with the hover effect: Below is the HTML code: <div class="portfblock"> &l ...

Is it possible to change the inner html to null during an active ajax request?

My goal is to have two separate data.html files inserted into two different HTML files without needing a click event. I want the structure of my data.html files to remain consistent, while allowing the template of my website to change dynamically by callin ...

Adjusting the font size on the Mui DatePicker's year picker for better styling and visibility

I've been struggling with customizing the styling of MUI's DatePicker, particularly the Year Picker. I experimented with two different methods for styling : Method 1 : Using MUI's createTheme() : MuiYearPicker: { styleOverrides: { ...

Implementing an active state for the initial item in jCarousel Lite

Is there a way to add a 'class="active"' state to the first element in the list when initializing jCarousel Lite without modifying the plugin? This is my current setup - $('#viewport').jCarouselLite({ speed: 500, visible: 3, ...

Utilizing HTTPS for OpenWeatherMap API in JavaScript encounters obstruction

I'm currently working on a project with free code camp where I am attempting to create a weather app using the OpenWeatherMap API. However, I have encountered an issue. My project needs to be submitted on Codepen and use HTTPS for geolocation. Due to ...

Creating a distinctive property with the standard settings

How can we ensure a unique property is generated for a mongodb/mongoose model upon creation? What would be the most effective method to verify if the created value is not already in use and generate an alternative value before saving? let schema = new S ...

The useDisclosure() function is not available in the Chakra UI library

An unanticipated runtime error occurred Error: (0 , chakra_ui_react__WEBPACK_IMPORTED_MODULE_2_.useDisclosure) does not seem to be recognized as a function I have verified that I am importing useDisclosure correctly from chakraUI, however I still receive ...

Can using display: none impact the SEO of a website's navigation menu?

Is there a difference in SEO impact between using display:none with CSS and using display:none with jQuery for menus? Appreciate the insights! ...

The integration of HTML and CSS using ng-bind-html appears to be malfunctioning

<ion-item ng-bind-html="renderHtml(word[key])"> </ion-item> When referring to word[key], it represents: <ul> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ul> This is the CSS being u ...

Exporting a web page as a Microsoft Word document is not working properly because

Need assistance with exporting a webpage to Microsoft Word in table format, as the table layout is not displaying correctly and is missing CSS styling. Can someone please help me resolve this issue? ...

CSS or jQuery: Which is Better for Hiding/Showing a Div Within Another Div?

Show only class-A at the top of the page while hiding all other classes (x,x,c). Hide only class-A while showing all other classes (x,x,c). Is it possible to achieve this? <div class="x"> <div class="y"> <div class="z"&g ...

Explore the next page on the API response by navigating to another page

In my next app, I have a versatile function called postAPI, which is used to send requests to the backend server. import Router from 'next/router'; export const postAPI = async ( endpoint, data = {}, headers = {}, method = 'POST&apos ...

Is the ajaxToolkit PopupControlExtender malfunctioning? Could it be due to being outdated?

I recently tried following a tutorial on using ASP.NET Ajax Popup Control to display GridView row details. However, I encountered a runtime error when attempting to perform a mouseover action. The error message reads: Sys.ArgumentUndefinedException: Va ...

Text displayed over an image using Bootstrap 5

I'm a beginner with Bootstrap 5 and I have a question about how to position text inside an image, similar to the first screenshot provided: https://i.sstatic.net/HVdie.jpg I tried using card-img but it didn't work. I also attempted to use cols, ...

Using Jquery to dynamically load an aspx page into a specific div element

Yesterday, I posted a question about loading an aspx page in a div tag. I have been using the code below to try and accomplish this, but so far I have been unsuccessful. Can anyone provide assistance on how to successfully load the aspx page into the div ...

Having trouble with React-table.js integration in Vue.js

I am attempting to incorporate the React Table library from into a Vue.js application using https://github.com/akxcv/vuera. This is my main.js: import Vue from 'vue' import { VuePlugin } from 'vuera' import App from './App&apo ...

The positioning and floating of two divs are set to fixed without using percentage width, however, the functionality is not

Apologies for my poor English writing :) I am attempting to float two divs side by side in a fixed position, without using percentages. This code works well on most browsers but is not compatible with IE 6. HTML <div class="right"></div> < ...

Converting a binary string encoded in either base64 or hex to an Int32Array

I am facing a challenge with transmitting a binary string over a ws websocket without using websocket.io. Currently, I am JSON.stringifying the data before sending it, like so: var msg.data = data.toString('base64') At the receiving end, I need ...