Utilizing CSS files to incorporate loading icons in a component by dynamically updating based on passed props

Is it possible to store icons in CSS files and dynamically load them based on props passed into a component?

In the provided example found at this CodeSandbox Link, SVG icons are loaded from the library named '@progress/kendo-svg-icons'.

Instead of loading icons directly from the library, is there a way to store these icons in a CSS file and inject them into components based on custom props?

For instance, in the following hypothetical scenario:

import from './ButtonStyles.css'
...
<React.Fragment>
....
<button icon="eyeIcon">Hello</button>
....
</React.Fragment>

Is there a method to achieve this functionality? Any sample code demonstrating this concept would be greatly appreciated.

Answer №1

Check out my solution

// In a CSS file named ButtonStyles.css, define the CSS classes for the icons:

.eyeIcon {
  background-image: url('path/to/eye-icon.svg');
}

.penIcon {
  background-image: url('path/to/pen-icon.svg');
}

// Import the ButtonStyles.css file in your component:

import './ButtonStyles.css';

// Create a function that links the icon prop value to the correct CSS class:
javascript

function getIconClass(icon) {
  switch (icon) {
    case 'eyeIcon':
      return 'eyeIcon';
    case 'penIcon':
      return 'penIcon';
    default:
      return '';
  }
}

// Utilize the getIconClass function to assign the CSS class to the button element based on the icon prop:

function Button({ icon, children }) {
  const iconClass = getIconClass(icon);

  return (
    <button className={iconClass}>
      {children}
    </button>
  );
}
// Implement the Button component with the icon prop:

<Button icon="eyeIcon">Hello</Button>

I hope this solution proves helpful to you

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

The specified React element type is not valid

Currently working on a web application using Typescript, Electron, Webpack, and NodeJS, but encountering issues with the import/export functionality. The error message that I am facing reads: "Warning: React.createElement: type is invalid -- expect ...

Tips for managing @ManyToMany relationships in TypeORM

In this scenario, there are two distinct entities known as Article and Classification, linked together by a relationship of @ManyToMany. The main inquiry here is: How can one persist this relationship effectively? The provided code snippets showcase the ...

How can I achieve the function of // @codekit-prepend "" with gulp?

I have recently started using gulp and I am familiar with codekit where I used to write // @codekit-prepend "foo.js" // @codekit-prepend "bar.js" to concatenate js files. Can someone guide me on how to achieve the same result with gulp? Below is the ...

Unveiling Insights from a JSON File: Data Extraction

I have a JSON file named pio2.json that contains the following data: { "controles":[{ "chart":[{ "type":"columns", "title":"Pollitos" }], "datos":[{"key":"Math","value":98}, {"key":"Physics" ...

Manipulating the length of an array based on a specified range using Vue.js

I'm currently working on a client's range filtering feature using Vue.js. The filter involves an input element with the type range to adjust the total number of clients displayed. I have successfully linked the value of the input to the **clients ...

Substitute the functions within a Node.js module with simulated functions

I am currently working on a Node.js project that serves as an API wrapper. To ensure the reliability of my code, I am writing unit tests using nodeunit and need to incorporate mock functions into the module. For instance, I require a function that mimics s ...

Verifying that the data has been successfully saved using JavaScript

When a user submits a small chunk of data via AJAX using a standard update action and a remote form, the information is sent to the action as javascript. The response is then rendered in javascript utilizing format.js. def update @message = Message.wher ...

How can Selenium be used to identify an Internet Explorer browser extension?

Can Selenium be used to detect internet explorer browser plugins? For example, if I open a URL on IE and want to check for any installed plugins, is there a way to automate this with selenium? ...

The AjaxPoller object is not defined and causing a TypeError

I have a piece of JavaScript code that handles AJAX requests and updates the DOM: this.AjaxHandler = { sendRequest: sendRequest, fetchDataForElement: fetchDataForElement, handleJsonResponse: handleJsonResponse, checkProgress: checkProgress }; fun ...

Implementing a dynamic update of an HTML element's content with JSON data - Learn how!

My task involves creating a quiz application where I need to show the answers along with images of the choices stored in my JSON data. However, I encounter an error: Uncaught TypeError: Cannot set properties of null (setting 'src') when I attempt ...

Steps for closing the menu by clicking on the link

My issue with the menu on the landing page is that it only closes when clicking the cross button. I want it to close when any link from the menu is clicked. I attempted to add code using querySelector, but it only worked for the home link and not the other ...

Streamlined approach to triggering ng-change on a single textbox

Consider this array within an angular controller: somelist = [ { name: 'John', dirty: false }, { name: 'Max', dirty: false }, { name: 'Betty', dirty: false } ]; To iterat ...

Troubleshooting: Angular 13 input radio not recognizing checked condition

Storing selectedKitchenId in localstorage, and checking if selectedKitchenId === kitchen.id to determine which radio button should be selected. Cannot figure out why the checked condition is not working as expected, even though when I use a strong tag to d ...

Reusing methods in Javascript to create child instances without causing circular dependencies

abstract class Fruit { private children: Fruit[] = []; addChild(child: Fruit) { this.children.push(child); } } // Separate files for each subclass // apple.ts class Apple extends Fruit { } // banana.ts class Banana extends Fruit { } ...

When integrating Stripe into my Next.js application, I encounter a build error

I encountered an error when building my Next.js app with Stripe integration using "yarn build". However, when running the app locally with "yarn dev", it works perfectly without any errors. I'm struggling to figure out why this discrepancy is happeni ...

Is there another way to retrieve a marketplace's product details using code?

When it comes to scraping products from various websites, I have discovered a clever method using window.runParams.data in the Chrome console. This allows me to easily access all the information without having to go through countless clicks to extract it f ...

Can the detectChanges() method in Angular cause any issues when used with the form control's valueChanges event?

Within my parent Component, I am working with a formGroup and updating its value using patchValue method. ngAfterViewInit() { this.sampleform.controls['a'].patchValue ...} I then pass this form to a child component in the parent component's ...

Tips for adding a button to the SB Admin 2 Card header without altering its height

I am currently utilizing the SB Admin 2 template for my project and encountering difficulty when trying to add a button in the card header without altering the default height. The goal is to maintain a consistent look across both cards, as illustrated in t ...

Toggle draggable grid in jQuery

Imagine I have a grid set up using the following code: $( "#dragIt" ).draggable({ grid: [ 15, 15 ] }); Now, there is a checkbox located below the div. Is there a way for me to switch the grid on and off by toggling the checkbox? I've searched the of ...

3 Methods for Implementing a Floating Header, Main Content, and Sidebar with Responsive Design

I am following a mobile-first approach with 3 containers that need to be displayed in 3 different layouts as shown in the image below: https://i.sstatic.net/UjKNH.png The closest CSS implementation I have achieved so far is this: HTML: <header>.. ...