How to customize the colors of imported images in next.js

In my next.js app, I designed a unique icon and uploaded it as an SVG file. Now, I am looking to add a feature that allows users to personalize the color of this icon by choosing from options like red, yellow, black, etc. However, since the image is static, I am unsure how to make this customization possible. Is there a workaround for achieving this?

https://i.sstatic.net/0BnXN.png

Answer №1

There are multiple approaches you can take when it comes to displaying SVG images:

  • Utilizing Webpack with @svgr/webpack
  • Using Babel with babel-plugin-inline-react-svg
  • Working with Next.js Image and using Dangerously Allow SVG in your next.config.js (although not recommended)

First and foremost, ensure that your SVG image is fillable. There are various resources available online to help guide you through this process.

Applies to each approach below (not repeated for spacing saving)

Incorporate the following code into the file where you want the SVG to be displayed

import Star from './star.svg'

const Example = () => (
  <div>
    // specify fill color and stroke is optional
    <Star height="100" width="100" fill="#6973ff" stroke="black" />
  </div>
)

Webpack (highly recommended)

A demonstration of this approach can be found on Codesandbox here

Code snippet sourced from react-svgr documentation

  1. Install yarn add --dev @svgr/webpack
  2. Add the following to your next.config.js file:
module.exports = {
  webpack(config) {
    config.module.rules.push({
      test: /\.svg$/i,
      issuer: /\.[jt]sx?$/,
      use: ['@svgr/webpack'],
    })

    return config
  },
}
  1. Refer to the code under In the file you want the SVG to show

Babel

Code snippet taken from the plugin repository

  1. yarn add -D babel-plugin-inline-react-svg

  2. Add the following to your .babelrc file:

{
  "plugins": [
    "inline-react-svg"
  ]
}
  1. Refer to the code under In the file you want the SVG to show

Next.js Image (Not recommended)

Here's an excerpt from Next.js explaining why this approach is not ideal:

The default loader does not optimize SVG images for several reasons. SVG is a vector format that can be resized losslessly, and it shares many features with HTML/CSS, which can pose security risks without proper Content Security Policy (CSP) headers.

Due to this information from Next.js, I will skip providing an example for this method as it overlaps with other recommended approaches.

If you still wish to explore this option, you can refer to their documentation.

Answer №2

To seamlessly integrate SVGs into your React project, consider using the SVGR package (). This tool allows you to convert SVG files into React components, making it easy to manipulate their properties such as fill by utilizing either the fill attribute or style prop.

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

Discover the process of utilizing Cypress to mock the useSession and getSession functions in Next.js when working with next-auth

My current challenge involves stubbing both frontend and backend calls to useSession() and getSession() using Cypress. Despite my efforts, the stubbed functions are not replacing the original functions or being called: https://i.sstatic.net/W83ep.png Th ...

Embed HTML code into a React/Next.js website

I've been given the task of enhancing the UI/UX for an external service built on React (Next.js). The company has informed me that they only allow customization through a JavaScript text editor and injecting changes there. However, I'm having tro ...

Access a separate file within the package.json directory using NodeJS

Currently, I am delving into NodeJS and have developed several microservices, with each one handling a distinct functionality. My primary concern is this: within my 4 microservices, each one possesses its own package.json file along with its dependencies. ...

Tips for customizing the background color in Material UI:

My website has a theme switcher that toggles between light and dark modes. Currently, it is set to default colors of black and white. How can I customize these colors to my own preference? View the code in SandBox Despite attempting to change the colors i ...

Display words on screen and then alter hue using HTML and CSS

Is there a way to dynamically change the color of text inside <a> tags from black to red after a specific time interval and keep it permanently red? do { document.getElementById("code").innerHTML +="<a>Hello World</a><br>"; awa ...

I am having trouble with retrieving and showing Json data in a table using axios within a React component

Struggling to access JSON data using hooks to display it in the <p> tag but encountering an error - "TypeError: states.map is not a function". I attempted utilizing Array.from() to convert my JSON to an array, yet it neither displayed anything nor pr ...

What could be causing my div link to redirect to different content instead of the intended destination?

When creating a div to provide information about a course, including the price and a "Take Class" button that links to the purchase page, I encountered an issue where the link extends beyond the intended area. @import url(https://fonts.googleapis.com/cs ...

What is the process for sending data from a client to fastapi's OAuth2PasswordRequestForm using a post request?

I am currently developing my frontend using nextjs and my backend using fastapi. I encountered an issue when running this code on the frontend: async function test() { const response = await fetch("http://127.0.0.1:8000/token", { meth ...

An in-depth guide on integrating d3 with reactJS and nextJS

I need help with adding a d3 chart to my React project. I've followed the tutorials, but nothing is showing up. I'm not sure if I'm using useEffect() at the right time, if I should be using componentDidMount instead, or if I'm just not ...

Customize the appearance of each TreeItem in JavaFX using CSS to assign unique

I am looking for a way to color individual Tree Items in a treeView based on specific conditions. I found a promising answer, but unfortunately, I am struggling to implement it. You can check out the answer here. My main obstacle is understanding how to u ...

Elevate column to top position in mobile display with Bootstrap

I am currently working with Bootstrap column classes and have set up four columns as follows: <div class="col-md-3"> @include('schedulizer.classes-panel') @include('schedulizer.time-span-options-panel') @include(&apos ...

Customize the base path for next-auth version 4

I have a new application that is using next-auth 4 to authenticate against Azure AD. Everything seems to be working well as I am able to successfully authenticate. However, when I attempt to set a custom base path http://localhost:3000/myapp for the appli ...

Can an element contain two different classes at the same time?

Apologies if the title was unclear. I am trying to customize the color of my font awesome social media icons individually. Although I have successfully changed the color for all of them, that is not the desired outcome. Here is the icon: <i class=& ...

Tips for showing grouped headers in MUIDatatable using React JS

enter image description here Looking at the image above, I am trying to display it in a muidatatable with grouped headers. I attempted to use the code below but was unsuccessful in creating a table with grouped headers; it only displayed the individual h ...

Adjust the parent div's background when hovering over it

Here is the code snippet I am working with: <div class="thumb_image_holder_orange"> <img src="http://dummyimage.com/114x64/000/fff.png" /> </div> I want to change the background of the div when hovering over the image, rather than j ...

`Enhancing the appearance of code in PHP`

I'm struggling with customizing the data pulled from the database. Can anyone provide assistance? I attempted to define $style within the while loop and assign it to $questions, but nothing is displaying on the webpage. While I have some familiarity w ...

Tips on incorporating several class names into Next.js elements

My current challenge involves an unordered list element with the following structure: <ul className={styles["projects-pd-subdetails-list"]}> {detail.subdetails.map((sub) => ( <li className={styles[ ...

What could be causing the link in my react application to malfunction?

While I have successfully added links in React apps before, this time I'm facing an issue where the page displays the image but the link itself isn't rendering. Could there be a mistake in my syntax? <a href src="https://soundcloud.com/us ...

What is the method to activate a function whenever a particular state is

I'm searching for a solution to associate a specific function with a change in a particular state. Here is the code I have written: export type MoviesAppState = { search: string; searchBy:string; startDate: number; endDate: number; } ...

Dynamic CSS overlay based on database field content without requiring user interaction

Is there a way to automatically display overlays for specific options in a database field using Bootstrap code? The options are SOLD, CONTRACT, and NO. I need different overlays to appear for SOLD and CONTRACT, while no overlay is needed for the NO option ...