Material UI - Array of Chips

I have been working on creating a ReactJS component that displays an array of chips with unique styling for each one. To achieve this, I created individual makeStyles classes for the chips. However, I encountered difficulties in dynamically changing the class for each chip. Here is what I have done so far:

    const classes = useStyles();
      const [chipData, setChipData] = React.useState([
        { key: 0, label: 'Heating' },
        { key: 1, label: 'Printing' },
        { key: 2, label: 'Resetting' },
        { key: 3, label: 'Idle' },
        { key: 4, label: 'Suspended' },
        { key: 5, label: 'Suspend in Progress' },
        { key: 6, label: 'Attention - Printer Connection Lost' },
        { key: 7, label: 'Attention - Filament Out' },
        { key: 8, label: 'Attention - Cooldown Failed' },
      ]);


      return (
        <Box display="flex" flexDirection="row" alignItems="flex-start" className={classes.container}>
          {chipData.map((data) => {



            return (
            <div classes={classes.chipContainer}>
              <li key={data.key}>
                <Chip
                  label={data.label}
                  if (label === 'Heating') {
                    className={classes.heatingTag}
                  }

                />
              </li>
              </div>
            );
          })}
        </Box>
      );
}
export default PrinterStatusTags

My approach includes using an if statement within the Chip element to assign specific classes based on the chip's label. I intended to have an if statement for each label, but I am facing the error message:

Parsing error: Unexpected token

I am open to suggestions on how to effectively assign classes based on each chip.

Answer №1

Revamped Answer

Here are two key improvements you can make:

  1. Introduce a new category attribute for each chip.
  2. Establish a mapping from the category (mentioned in point 1) to the respective styles.
const styleMapping = {
   first: styles.firstStyle,
   second: styles.secondStyle
   // ...
};

const [chipData, setChipData] = React.useState([
        { key: 0, label: 'Heating', category: 'first' },
        { key: 1, label: 'Printing', category: 'second' },
      // ....
      ]);

Once the association between each chip and its category is defined, proceed with rendering:

return (
        <Box display="flex" flexDirection="row" alignItems="flex-start" className={styles.container}>
          {chipData.map((data) => {
            return (
            <div className={styles.chipContainer}>
              <li key={data.key}>
                <Chip
                  label={data.label}
                  className={styleMapping[data.category]} />
              </li>
              </div>
            );
          })}
        </Box>
      );

Previous Response

To enhance your code, consider these recommendations:

  1. Utilize the className attribute instead of class (or classes).
  2. Implement the condition within the className property. Keep in mind that there are more efficient ways to assign the appropriate class, but this solution should suffice for now.

This snippet showcases the corrected version:

<div className={styles.chipContainer}>
      <li key={data.key}>
         <Chip label={data.label} className={ data.label === 'Heating' && styles.heatingTag}/>
      </li>
   </div>   

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

Iterate through the list elements by utilizing jQuery

I am working with HTML code that looks like this: <ul class="lorem"> <li>text</li> <li>text</li> <li>hello</li> <li>text</li> </ul> Can someone help me figure out how to loop through ...

Guide to importing firebase-functions and firebase-admin using ES6 syntax for transpilation with Babel in Node 10

I've been working on my cloud functions in ES6 and using Babel to transpile them for the Node v10 environment. But, I've come across an odd issue. It seems that when I import firebase-functions like this: import functions from 'firebase-fu ...

Detecting single letters in a sentence and changing their appearance using CSS

Looking to make a subtle change to text? I need to swap out single letters in a passage (I have a cat that ate a fish). Any ideas on how to do this? The goal is to input a block of text into a textbox, then display it in a div. I've had difficulty fi ...

Issue with inserting data into MySQL database using Node.js (JavaScript)

I am attempting to utilize the insert function but keep encountering an error. I want to add a user's name to the user table. The function I am using is: function insert(tableName, toField, value){ connection.connect(); var queryString = "i ...

Access and play audio files from a blob storage using Azure Functions in a React application

I have been working on integrating an audio file from azure storage into my react app using the react-h5-audio-player library. Below is the code snippet of my azure function: import { AzureFunction, Context, HttpRequest } from "@azure/functions" ...

Text-color in the v-tooltip

Is there a way to change the text color of v-tooltips components without affecting the tooltip background color? I attempted to inspect the element, but the tooltip only appears on hover, making it impossible to inspect. Below is the code snippet: < ...

Ionic 4: Facing issues with setting complete background image on ion-card

https://i.stack.imgur.com/3lH6h.png I'm currently attempting to set a background image for an Ion-card in order to completely cover the card's area. However, I'm facing an issue where the background image does not cover the entire area and ...

Deactivating one div's class upon clicking on another div

Below is the HTML code snippet: <div class="container"> <ul class="navbar"> <li class="nb-link"><a>Home</a></li> <li class="dropdown"> <a>CBSE</a> <ul class="dropdown-menu"&g ...

Animate failed due to the appending and adding of class

$('#clickMe').click(function() { $('#ticketsDemosss').append($('<li>').text('my li goes here')).addClass('fadeIn'); }); <link href="http://s.mlcdn.co/animate.css" rel="stylesheet"/> <script ...

Storing the output of asynchronous promises in an array using async/await technique

I am currently working on a script to tally elements in a JSON file. However, I am encountering difficulty in saving the results of promises into an array. Below is the async function responsible for counting the elements: async function countItems(direct ...

Having issues with setting up Gitlab CI with VITE environment variables

I've extensively researched (including official documentation and countless online resources) and experimented with various methods, but I'm struggling to grasp environment variables in VITE when using Gitlab pipelines. It worked seamlessly with ...

Utilizing getServerSideProps in the new app router (app/blah/page.tsx) for maximum functionality

I am a beginner in Next.js and I am currently experimenting with the new app router feature by placing my pages under app/.../page.tsx The code snippet provided works when using the page router (pages/blah.tsx) but encounters issues when used in app/blah/ ...

Only apply the CSS filter alpha to the parent element and not its children

I am working on implementing an alert message box using HTML and CSS. Below is the code I have so far: <div class="dim" id="msg"> <div class="dialog_wrapper"> <div class="dialog" id="msg_value"></div> ...

What methods can I use to maintain alignment across different screen sizes?

html, body { height: 100%; width: 100%; margin: 0; padding: 0; overflow: hidden; } .container { position: absolute; width: 100%; height: 100%; ...

Using single-spa with Angular Parcel inside a mat-dialog

I have developed an Angular application and an Angular parcel that will be utilized by various applications within the organization utilizing different frameworks. When I try to display the parcel component directly in another component using the async c ...

Creating a multilingual 404 page with NextJS 13: A step-by-step guide utilizing route groups

I've been having trouble implementing the localized not-found page in NextJS 13 (app-dir). I'm following the official guide on internationalization, as well as this solution I found on GitHub: this. First Attempt: [locale] -- [...not-found] ...

Sliding divider across two div containers with full width

Seeking a JavaScript/jQuery function for a full page slider functionality. The HTML structure I'm working with is as follows: My objectives are twofold: Both slide1 and slide2 should occupy the full width of the page. Additionally, I am looking for ...

What is the best method for retrieving text from the aria-label attribute?

Currently, I am delving into the world of web scraping. My goal is to extract the work-life balance rating from the Indeed website. However, the main obstacle I'm encountering is the extraction of text from the aria-label attribute so that I can retri ...

Steps to modify the button color within a sub-menu by leveraging vue js3 and element-plus

After creating a button in a sub-menu that should change color when clicked, I am struggling to make it work. Below is the code for the button: In addition to this code snippet, I have added more code which can be found here I also want to change the co ...

Switching Unicode icon when element is clicked

My form has two inputs - one for text input and the other for submitting, like a button. I have added an icon to the submit button and want it to change when clicked. <input class="searchBtn" id="submit" name="submit" type="submit" value="&#xf002"& ...