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

The type 'FormikValues' is deficient in the subsequent properties compared to the type 'Exact<{'

I am currently working on a form with the following structure: import { Field, Form, Formik, FormikProps, FormikValues } from 'formik' import { NextPage } from 'next' import React from 'react' import { useCreateUserMutation } ...

Tips for inserting a delay between two separate javascript commands within the same onchange event

Within my HTML code, I have an input field that triggers an onchange event: <input type="text" value="2014-01-01" class="datepicker dateDashboard" onchange="repartiteur('DatesDashboard',$(this));document.location.href='index.php?menu=17| ...

Unable to launch React Native project on emulator now

Something seems off with my App as it won't start up on my AS Emulator. Everything was running smoothly yesterday, but today it's not working - possibly due to me moving the npm and npm-cache folders, although they are configured correctly with n ...

How to Center a DIV both Vertically and Horizontally with CSS Positioning?

I'm currently working on a webpage layout where I want to have a main div centered horizontally with three smaller divs inside, aligned both vertically and horizontally with equal spacing. I tried using margin: auto on an empty div to center it in the ...

Express router route encountered a 404 Error

The first API endpoint is functioning correctly, however when attempting to access the second route, I am encountering a 404 error. Upon sending a GET request to http://localhost:3000/api/posts/, the response received is as follows: { message: "TOD ...

What could be causing WidgEditor, the JavaScript text editor, to fail to submit any values?

After clicking submit and attempting to retrieve text from the textarea, I am encountering a problem where the text appears blank. The reason for this issue eludes me. function textSubmit() { var text = $("#noise").val(); console.log(text); consol ...

Is it possible to include a value for the "src" attribute rather than the "class" attribute in the array of values in list.js?

Check out the HTML code I wrote: <html> <head> </head> <body> <input class="search" placeholder="Search" /> <div id="users"> <ul class="list"> ...

Simple steps to integrate Facebook chat messenger into Next.js

I've been attempting to integrate Facebook customer chat into my Next.js app, but I'm encountering issues. Despite thoroughly reviewing my code, I can't seem to identify the problem. What is the correct method for adding Facebook customer c ...

Assigning event to the body element

Is there a way to bind an event to the entire page, specifically the html or body tag? I am trying to achieve the following: document.addEventListener('mousemove', function() { alert('a'); }); I want an alert to be triggered whenever ...

Is the translation pipe in Angular 5 impure?

I'm currently utilizing ngx-translate. Can you tell me if the translation pipe is considered pure or impure? Also, would it be more beneficial to use the directive syntax translate="X" instead? ...

The Art of Checkbox Design

Seeking help in replacing the default check mark on a checkbox with an image. Here is the code snippet I am currently using: <html> <head> <style> .bl { background:-webkit-gradient(linear, left top, left bottom, color-stop(0, #175899), c ...

JavaScript - Combine objects by summing values with matching keys

Below is the given array : [ { "Date": "2019.07.08", "Organisation": "A", "Client": "Client1", "Product": "Pen", "Quantity": "1120" }, { "Date": "2019.07.08", "Organisation": "A", "Client": "Client1", "Product": " ...

Challenge with CSS3 Selectors

I'm struggling to understand why this code works: input[ type = "text" ]:last-of-type:focus{ border:1px solid red; } but this code doesn't work: input[ type = "checkbox" ]:last-of-type:checked{ border:1px solid red; } The example given with t ...

Tips on effectively utilizing dynamic data with Google Charts

I am working on creating a dynamic chart using Google Charts with multiple CSV files. I want to display a different chart depending on the selection made by the user. The first file loads successfully and displays a chart, but the $("#selection").change(.. ...

MYSQL table successfully created, however encountering a 500 error when attempting to post data

I've been working with the Node module KNEX for making MYSQL calls, and I'm trying to allow users to add their own custom tables. I have successfully added a database to MYSQL with all the necessary columns, but unfortunately, I keep encountering ...

Ways to extract pertinent information from a PHP API

I've been attempting to add parameters to my query, but I keep getting inconsistent results. Despite trying different methods, I haven't been successful. Take a look at the code below. First, here is my code that functions properly without using ...

What is the best method to incorporate extra parameters into highcharts using data extracted from datatables?

I have a query regarding the integration of datatables with highcharts. The issue I'm facing is related to specific configurations for chart-A, which is of column type. Even after applying the configurations, it seems like they are not being incorpora ...

Pull the data from jQuery/JavaScript/AJAX and store it in the database using ASP.NET/C#

I am working on creating a form that includes textboxes and a five star rating feature. The goal is to save the data entered in the fields into a database upon submitting. While implementing the textboxes was straightforward, I am facing challenges with e ...

I am looking to implement a permanent change using PHP Ajax

I am facing an issue with the "Add as Buddy" button on my webpage. I want it to change permanently to "Pending Request" once clicked, but it keeps reverting back to "Add as Buddy" whenever I refresh the page. Can anyone suggest a solution for this problem? ...

How can I prevent clicks on child links using the :not() selector?

I am working on a script using JQuery where I want to add a click handler to a div while ignoring clicks on the children a tags within it. You can check out my attempt (which is not working as expected) on this JSFiddle link: http://jsfiddle.net/q15s25Lx/ ...