Guide to updating material ui icon based on the server's feedback

In my table, there is a column labeled status. The backend returns three values for this column: "approve", "Review", and "pending". I am trying to change the icon shape based on the status value. Specifically, when the status is "approve", I want to use the VerifiedUserIcon (imported from '@material-ui/icons/VerifiedUser';). When the status is Review, I want to change the icon shape to VisibilityIcon, similar to the example in this picture:

https://i.stack.imgur.com/iApaZ.png

How can I achieve this?

<TableCell className="p-4 md:p-16 truncate" component="th" scope="row">
  <Chip
    style={{ fontSize: "1.2rem" }}
    icon={<FaceIcon />}
    label={n.status}
    variant="outlined"
  />
</TableCell>;

Answer №1

function displayIcon(status) {
  switch (status) {
    case "verified":
      return <VerifiedIcon />;
    case "review":
      return <ReviewIcon />;
    default:
      return <DefaultIcon />;
  }
};

<TableCell className="p-4 md:p-16 truncate" component="th" scope="row">
  <Chip style={{ fontSize: "1.2rem" }} icon={displayIcon(n.status)} label={n.status} variant="outlined" />
</TableCell>;

Answer №2

Another option is to utilize the ternary operator for defining icons, especially when dealing with only 3 different states

<TableCell className="p-4 md:p-16 truncate" component="th" scope="row">
  <Chip
    style={{ fontSize: "1.2rem" }}
    icon={
      n.status === "approve" ? (
        <VerifiedIcon />
      ) : n.status === "review" ? (
        <ReviewIcon />
      ) : (
        <PendingIcon />
      )
    }
    label={n.status}
    variant="outlined"
  />
</TableCell>;

Answer №3

If you want to customize your icons, consider using Object literals to map status with related icons as shown below.

const statusIcon = {
  verified: <VerifiedIcon />,
  review: <ReviewIcon />,
  // You can add more icons based on your status
};

In your code, simply use the statusIcon object to retrieve the correct icon based on the property.

<TableCell className="p-4 md:p-16 truncate" component="th" scope="row">
  <Chip
    style={{ fontSize: "1.2rem" }}
    icon={statusIcon[n.status]}
    label={n.status}
    variant="outlined"
  />
</TableCell>

Answer №4

Instead of creating a list with every available icon, it might be better to approach it differently:

import * as Icons from '@material-ui/icons'

<TableCell className="p-4 md:p-16 truncate" component="th" scope="row">
  <Chip
    style={{ fontSize: "1.2rem" }}
    icon={React.createElement(Icons[YOUR_ICON_NAME])}
    label={n.status}
    variant="outlined"
  />
</TableCell>;

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

After deploying to Firebase hosting, the next/image component is not showing any images

While my images load and display correctly on npm run dev, they do not show up after deploying my project. I have been using next/image to upload the images, storing them in an Assets folder with a format of src='/Assets/car.jpg'. How can I res ...

I tried utilizing the useState hook to store the value, but surprisingly, it failed to update

I am brand new to Reactjs and currently working on creating an address form that includes 3 select options for country, state, and city. I have implemented React hooks in my project, where the page fetches a list of countries upon initial load. Subsequentl ...

Difficulty accessing context.params query in Next.js Dynamic Path

I've almost completed setting up a dynamic page in Next.js using getStaticPaths(), but I'm running into an issue with the getStaticProps() function not referencing the URL query correctly to load the relevant information. Here is my code: //Get ...

Designing a calendar with a grid template

I am attempting to design a calendar that resembles an actual calendar, but I am facing an issue where all created divs (representing days) are being saved in the first cell. I am not sure how to resolve this. Any help would be greatly appreciated. css . ...

Can getServerSideProps be adjusted to avoid triggering a complete page reload after the first load?

My server-rendered next.js app consists of a 3-page checkout flow. The first page involves fetching setup data like label translations and basket items within the getServerSideProps function, as shown below: UserDetails.js import React from 'react&apo ...

Unable to utilize mobs decorator as an error is occurring: Experimental syntax 'decorators-legacy' is not enabled at the moment

Having successfully used mobx decorators in a React Native project, I now encounter an issue while developing a website with the React.Js library. The error message states: Support for the experimental syntax 'decorators-legacy' isn't curre ...

Is there a way to instruct npm to compile a module during installation using the dependencies of the parent project?

I am curious about how npm modules are built during installation. Let me give you an example: When I check the material-ui npm module sources on GitHub, I see the source files but no built files. However, when I look at my project's node_modules/mate ...

"Encountering issues with the build process in npm

While attempting to develop my web app using react and node.js, I encountered a persistent issue after updating packages. The error message I am facing is: Module not found: Error: Can't resolve 'fs' in 'my-app/node_modules/dotenv/lib ...

Understanding the process of extracting multiple parameters from dynamic routing in Next.js

Consider the following folder structure: - src - pages - jobs - [id].js If we have a URL like this: http://localhost:3000/jobs/123 You can access 123 inside the [id].js page. Now, what if we need to add another parameter called ti ...

The useNavigate() hook from react-router-dom is not properly setting the id in the URL path

I am currently using react-router-dom v6 for my routing needs. My goal is to pass an ID in the navigate URL path. Here is the onClick method and button code that I am working with: let navigate = useNavigate(); const routeChange = (id) => { let ...

Step by step guide on integrating ReactJS into your current node.js backend application

I am currently working on a basic node.js API Setup: | project-name | public | index.html | ... some static js/css | app.js | package.json app.js var express = require('express'), bodyParser = require('body-parser'), ...

Guide to positioning a div in the center while implementing animations through transition and transformation using scale

Creating a popup for my React app without relying on external libraries is my current project. I am experimenting with using transition and transform with scale to size the popup dynamically based on screen size and content, then center it on the screen. ...

Placing a button above another element using CSS styled components

I'm attempting to make a button overlap and be positioned in a specific location on top of a search bar. The current appearance is not what I desire, as the button seems to shift back to its original position when adding a :hover element after applyin ...

What is the best way to create an optional object parameter in Typescript?

I'm working on a function that looks like this: const func = (arg1: string, { objArg = true }:{ objArg: string }) => { // some code } Is it possible to make the second parameter (an object) optional? ...

Strategies for Improving Usual React Components

When styling a mandatory TextField, you can refer to this example const styles = theme => ({ labelAsterisk: { color: "red" }, cssLabel: { color: "orange" }, cssRequired: { "&:before": { borderBottom: "2px solid orange" ...

Unlocking the contents of an array from a separate file in Next.js

I am developing a Quiz App that consists of two main pages: takeQuiz.js and result.js. My goal is to transfer the data from the multiple-choice questions (mcqs) in takeQuiz.js to be accessible in result.js. Utilizing router.replace(), I ensure that once th ...

In react-native, both the parent and child components are rendered at the same time

One of my components, the parent one, goes through an array of chapters and for each item found, renders a child component called 'ExercisesList' and passes an array of exercises to it. class ExercisesScreen extends Component { displaySelected ...

Is there a way to modify the route or file name of the index.html file in a React project?

Every time I use npm build to create a React app (using the typical react-scripts/create-creact-app, etc.), the entry file always ends up in build/index.html. I attempted to move the src folder into a subfolder, but unfortunately, index.js must remain in ...

Prevent modal from closing upon clicking a select option

After creating a customized filter for MUI's datagrid, I encountered an issue where the two select options in the filter were too large and ended up extending outside the modal. Whenever I clicked on an option, the entire modal would close unexpectedl ...

React - Attempting to access property X from an undefined variable

Trying to access the string in section1.text, but my console is showing: https://i.stack.imgur.com/ox8VD.png Here's the JSX code I'm using: return ( <div> <h1>{this.props.article.title}</h1> ...