Changing the fill color of externally imported SVGs from a CDN: A simple guide

While working on a website project using Next JS, I came across the challenge of displaying SVG icons stored in Sanity and dynamically changing their fill color. Is it possible to achieve this feature, such as changing the color when hovering over the icon?

Let me provide an overview of my code to give context to what I am attempting:

const [icon, setIcon] = useState('');

useEffect(() => {
    const query = '*[_type == "socials"]'

    client.fetch(query)
      .then((data) => {
        setIcon(urlFor(data.icon).width(24).url());
    });
}, []);

<NextImage
    useSkeleton
    src={icon}
    width='24'
    height='24'
    alt='name'
/>

It is worth noting that the NextImage component used above includes a skeleton loading effect.

The code successfully displays the SVG icons from Sanity, but I am struggling to implement a hover effect to change the color dynamically. This is the issue I need assistance with.

Here are the SVG icons currently displayed:

https://i.sstatic.net/N15iP.png

I aim to have the ability to alter the color of these icons programmatically without modifying the SVG files already uploaded to Sanity.

Answer №1

To style SVGs, they must be inlined into the HTML rather than being accessed through an <img> tag or external URL.

If you have the SVG markup from the image URL, you can inline it into the HTML by fetching the original SVG URL (without using the .width() function).

After obtaining the SVG URL (ending with .svg and displaying the SVG markup when visited), fetch the data using fetch() or any preferred method, then utilize dangerouslySetInnerHTML to insert the returned SVG markup into a <div>. (Ensure the source of the images is trusted, or sanitize if necessary.)

The styling of the SVG will vary based on your application's style management and the specific SVG. An example could be:

/* target svgs inside a div with class "inline-svg" */
div.inline-svg svg {
  color: black;
  width: 24px;
  height: 24px;
}
div.inline-svg:hover svg {
  color: red;
}

This approach works well for SVGs that have fill="currentColor" or stroke="currentColor" attributes depending on their structure.

Answer №2

For those utilizing Simple Icons, it is possible to specify the color according to the instructions provided on their GitHub page:

<img src="https://cdn.simpleicons.org/linkedin/00ccff99" width="32"/>
<img src="https://cdn.simpleicons.org/github/red" width="32"/>

This results in:


Enjoy!

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

Is there a solution available for the error message that reads: "TypeError: Cannot set value to a read-only property 'map' of object '#<QueryCursor>'"?

Everything was running smoothly in my local environment, but once I deployed it on a Digital Ocean Kubernetes server, an error popped up. Any assistance would be greatly appreciated. https://i.stack.imgur.com/VxIXr.png ...

I encountered an issue with my TypeScript function in Angular, as it is unable to process multiple uploaded files

I'm having trouble with my TypeScript function in Angular that is unable to read multiple uploaded files. fileUpload(event: Event) { const self = this; this.imageUploadInp = event.target as HTMLInputElement; this.imageUploadInp.addEventLis ...

Contrasting the Next 12 client-side routing with the Next 13 server-centric routing

According to the Next 13 documentation, it explains how the new router in the app directory utilizes server-centric routing to align with Server Components and data fetching on the server. Unlike the traditional pages directory that employs client-side r ...

What could be the reason for receiving the error message "NgModule' is not found" even after executing the command "npm i @types/node --global"?

Even though I tried following the suggestions provided in this Stack Overflow thread, I am still encountering the error "TypeScript error in Angular2 code: Cannot find name 'module'". My development environment consists of Angular 5 and npm versi ...

Adding Dependencies to a Static Factory in Typescript

I have developed a service in typescript as a Class. Within this class, I have defined a static Factory where dependencies are injected. However, when I compress my application, the dependencies get compressed too, leading to an undefined provider error. ...

Issue with Formgroup in Angular Reactive Form - Validation not functioning as expected

I am working with a form group which is defined below: get createItem(): FormGroup { return this.formBuilder.group({ name: ['', Validators.required], email: ['', Validators.required], mobile: ['', V ...

I need to confirm the validity of minDate and maxDate in a ReactJS component, ensuring that maxDate is always at least 5 years after min

start from today and select a date end 5 years from the starting date I haven't attempted anything yet. Seeking help for a solution. ...

The navigation bar is struggling to be positioned on top of the body

I have encountered an issue where I want my navbar to remain on top of all components, but when I open the navigation menu, it pushes all the components of the index page down. My tech stack includes Next.js, Tailwind CSS, and Framer Motion. This problem ...

Learn how to retrieve category page information within a component in Next.js!

I have a plan to develop a category page that will display all tags added to articles. By clicking on a specific tag, it should show a page with all articles containing that particular tag. For this project, I am using Next.js, SSG, and pulling the articl ...

MongoDB MongooseError: The `collection.aggregate()` method cannot be called until the initial connection is fully established

Check out my personal website that I created using NextJS and hosted on Vercel. The site connects to a MongoDB database through Mongoose in my NodeJS API. Recently, I've been encountering a strange error affecting only about 1% of the users: Mongoose ...

NextJS is throwing an error when trying to access the value returned

I've been exploring next.js and am trying to implement useContext for managing global state. However, I'm encountering difficulty in passing the value from provider to child element as the returned value of language in header.js is coming up as u ...

Issues arising when routing ffmpeg to flac encoder

I am facing an issue with encoding a flac file with seektables. The ffmpeg's flac encoder does not include seektables, so I have to resort to using the flac Command Line Interface (CLI). My goal is to convert any arbitrary audio file into a seekable f ...

Inputting data types as arguments into a personalized hook

I am currently developing a Next.js application and have created a custom hook called useAxios. I am looking to implement a type assertion similar to what can be done with useState. For example: const [foo, setFoo] = useState<string>(''); ...

Using Google Fonts in a Typescript React application with JSS: A step-by-step guide

How can I add Google fonts to my JSS for use in styling? const styles = ({palette, typography}: Theme) => createStyles({ time: { flexBasis: '10%', flexShrink: 0, fontSize: typography.pxToRem(20) }, guestname: ...

A step-by-step guide on integrating Azure Cognitive Search within a SharePoint Online SPFx webpart

I haven't had much experience with SPFx recently, so it looks like I'll need to brush up a bit. :) I'm interested in implementing this NPM package: https://www.npmjs.com/package/azure-search Within a simple new SPFx web part: The code ...

Can the locale in URLs be concealed for localized routing with NextJS?

Looking for a Solution I'm seeking a method to maintain a consistent visible URL for the user while implementing internationalization capabilities. The Scenario I'm Facing I aim to provide seamless access to pages for users and conceal language ...

Encountering Error when Attempting to Load Webpack Dependencies for Browser

I'm currently in the process of manually scaffolding an Angular 6 app (not using the CLI). Everything was going smoothly until I encountered a webpack error: ERROR in window is not defined After researching online, it seems like I may be missing som ...

Encountering an issue during the registration of reducers with ActionReducerMap: "does not match the type 'ActionReducerMap<AppState, Action>'"

Here is a simplified version of my Angular 5 application. I have a reducer that needs to be registered in the root module. The problem arises in LINE A where I encounter the following error: ERROR in src/app/store/app.reducers.ts(7,14): error TS2322: Type ...

Compelled to utilize unfamiliar types in TypeScript generics

When working with a Typescript React form builder, I encountered a situation where each component had different types for the value and onChange properties. To tackle this issue, I decided to utilize generics so that I could define the expected types for e ...

Displaying images in ReactJS, NextJS, or Tailwind UI may not be straightforward

I am facing an issue with changing the image sourced from "https://tailwindui.com/img/logos/workflow-mark.svg?color=indigo&shade=600". Every time I try to replace it with a local image from my directory, only a default image appears. Does anyone have a ...