Tips for coding in Material-UI version 5: Utilizing the color prop in the Chip component by specifying

Is there a better way to type the MUI Chip prop color when the actual value comes from an object? Using any doesn't seem like a good option. Additionally, is keyof typeof CHIP_COLORS the correct approach for typing?

import { Chip, Stack } from "@mui/material";

const DATA = [
  {
    id: 2,
    status: "success"
  },
  {
    id: 3,
    status: "finished"
  },
  {
    id: 4,
    status: "error"
  }
];

const CHIP_COLORS = {
  finished: "primary",
  error: "error",
  success: "success"
};

export default function App() {
  return (
      <Stack
        sx={{gap: 5}}
      >
        {DATA.map(({ id, status }) => {
          return (
              <Chip
                color={CHIP_COLORS[status as keyof typeof CHIP_COLORS] as any}
              />
          );
        })}
      </Stack>
  );
}

Codesandbox: https://codesandbox.io/s/festive-breeze-s4vpfk?file=/src/App.tsx

Answer №1

you have the ability to define custom types.

type eventType = "finished" | "success" | "error";
type colorType = "primary" | "error" | "success" | "default" | "secondary" | "info" | "warning" | undefined

the data structure you're working with:

const DATA:{ id:number, status:eventType }[] =  [
  {
    id: 2,
    status: "success"
  },
  ...

defining chip colors based on event type:

const CHIP_COLORS: { [key in eventType]: colorType } = {
  finished: "primary",
  error: "error",
  success: "success"
};

how it's rendered within a component:

{DATA.map(({ id, status }) => {
        return (
         <>
           <Chip color={CHIP_COLORS[status]} />
          </>
        );
 })}

https://codesandbox.io/s/wild-cloud-6q050i?fontsize=14&hidenavigation=1&theme=dark

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

Avoid the import of @types definition without exports in TypeScript to prevent the error TS2306 (not a module)

I have spent a considerable amount of time trying to load a NodeJS library that has what I believe is a faulty type definition in the @types repository. The library in question is geolib and its types can be found in @types/geolib Although I am aware tha ...

Adjusting the audio length in React/Typescript: A simple guide

I'm currently developing a web app with React and TypeScript. One of the components I created is called SoundEffect, which plays an mp3 file based on the type of sound passed as a prop. interface ISoundEffectProps { soundType: string, // durat ...

Revamp your search experience with Algolia's Angular Instant Search: Design a personalized search box template

Custom Search Box Request: My goal is to implement an autosuggest search box using Algolia Angular instant search with an Angular Material design. To achieve this, I am planning to customize the search box component by replacing the standard <ais-sea ...

Instructions on transferring information from the app.component to its child components

I am currently working with Angular 6 and I have a specific requirement. I need to send data retrieved from an external API in my app.component to other child components. Instead of repeatedly calling the common API/service in every component, I want to ma ...

Looping through NavItems component using JavaScript or Angular

My Angular project includes a navbar component with an app sidebar that has a navItems attribute. Below is the content of my navBar: <app-header style="background-color : #e65100;" [fixed]="true" [navbarBrandFull]="{ src: &a ...

"Enhance your React app with stunning typography and

Is it possible to achieve a text underline effect in Typography like this? https://i.stack.imgur.com/5Eukj.png Here is the code I am currently using: <Typography variant="p" sx={{ letterSpacing: '1.5px', ...

Is it possible to link only one button to submit within a form containing two buttons?

One unique challenge I encountered in my React app is the need to connect only one button out of two to a form submission task. Currently, both buttons trigger the data submission process. Here's an example of the code: <div> <h2>cre ...

Notify user when Redux action is completes in ReactJS/Redux application

I've been working on a custom notification component that should display a message and then hide itself after a few seconds when certain redux actions, like login_fail, are triggered. However, I'm facing an issue where the message briefly pops up ...

How to customize the preview grid design in material-ui-dropzone

I am working on a book form page in my React app which includes an option to upload a cover photo. I opted for material-ui-dropzone from https://yuvaleros.github.io/material-ui-dropzone/ and it's working well, but I encountered an issue with the previ ...

Error: Unable to cast value "undefined" to an ObjectId for the "_id" field in the "User" model

Whenever a user logs into their account, I am trying to retrieve their data on the login screen. The login functionality itself works perfectly, but unfortunately, the user data is not displaying. I have tried troubleshooting this issue by making changes i ...

The information stored in Flask sessions is not retained across different sessions

Currently, I am constructing a website using React alongside Python with Flask. An issue has arisen where the session data is being lost between sessions and the cause remains unknown. Within the app.py file in Python, you can find the following app confi ...

Fetching data from the server in NextJS based on user input

After assembling a Client and a Server component (using App Router), I was able to refresh the Server when the user interacts with it, triggering a route refresh by using: router.push(pathname) Although that worked well for refreshing the Server, now I ne ...

Unraveling the intricacies of the relationship between `extends` and function types in TypeScript

Example 1 seems clear to me type A = (1 | 2 | 3) extends (infer I) ? [I] : never; // A = [1 | 2 | 3] In Example 2, the type variables are being intersected but I'm unsure why type A = ( ((_: 1) => void) | ((_: 2) => void) | ((_: 3) => ...

Provider not found: ConnectionBackend – NullInjectorError

I encountered the following error while attempting to load the webpage. Despite trying various suggestions from other sources, I have been unable to find a solution. Below the error stack lies my code. core.js:7187 ERROR Error: Uncaught (in promise): Null ...

The NVD3 chart embedded in a React application generates HTML elements that persist on the page indefinitely without fading away

In my React application, I integrated an NVD3 scatter chart. However, I have encountered an issue with the tooltip not disappearing when hovering over the chart: https://i.stack.imgur.com/6lLok.png After moving the cursor away from the chart, the tooltip ...

Uh oh! It appears that the Nextjs stripe-webhook api endpoint is missing. Error

Recently, I have been encountering a [404] POST http://localhost:3000/api/stripe-webhook error while listening on stripe. I am currently running the NextJs version "14.1.3". The stripe-webhook.ts file is located at 'app/api/stripe-webhook.t ...

Trouble with ReactJS render not reflecting changes in get function

Recently, I made some updates to the authentication process on my server for my single-page express/react app. However, when running the express server, I noticed that the updated .get function was not being served by my app. Do you have any ideas on why t ...

What is the reason behind the restriction on using capital letters in React project names?

When attempting to create a new project "newRecipeApp" in React, I encountered the following message: npx: installed 91 in 29.359s Could not create a project called "newRecipeApp" because of npm naming restrictions: * name can no longer contain capital ...

How can you incorporate TypeScript's dictionary type within a Mongoose schema?

When using TypeScript, the dictionary type format is: { [key: string]: string; } However, when I try to define a custom schema in mongoose, it doesn't work as expected. const users = new Schema({ [key: string]: String, }); I also attempted t ...

What is the best way to make changes to the DOM when the state undergoes a

I've programmed the box container to adjust dynamically based on input changes. For instance, if I entered 1, it will generate one box. However, if I modify the input to 2, it mistakenly creates 3 boxes instead of just 2. import React from 'rea ...