Katie7
Katie7

Reputation: 879

How do you insert a variable class name in Material UI?

I am trying to create a component which has a different coloured background depending on the data. For this I need a variable class, but I can't get it to work and would appreciate some help.

I just want a class to say either ragR, ragA or ragG (so the last letter is the variable).

Here is my code:

import React from 'react';

const useStyles = makeStyles(theme => ({
ragChip:{
  padding: 2,
},
  ragR: {
    backgroundColor: theme.palette.error.dark,
  },
  ragA: {
    backgroundColor: theme.palette.warning.dark,
  },
  ragG: {
    backgroundColor: theme.palette.success.dark,
  },
}));

const getRAG = ragStatus => {
  const rag = ragStatus.toString().toUpperCase();
  if (
    rag === 'RED' ||
    rag === 'AMBER' ||
    rag === 'GREEN' ||
    rag === 'R' ||
    rag === 'A' ||
    rag === 'G'
  )
    return rag.charAt(0);

  return 'U'; 
};

const RAGChip = ({ ragStatus }) => {
  const classes = useStyles();
  return (
      <Chip
        size="small"
        label=''
        className={`${classes.ragChip} ${classes.rag ${getRAG(ragStatus)}}`}
      />
  );
};

export default RAGChip;

Many thanks for your help!

Katie

Upvotes: 1

Views: 1636

Answers (1)

Taghi Khavari
Taghi Khavari

Reputation: 6582

I think what you need to do is this:

const getRAG = (ragStatus) => {
  const rag = ragStatus.toString().toUpperCase();

  if (rag.startsWith("R") || rag.startsWith("A") || rag.startsWith("G")) {
    return rag[0];
  }

  return "U";
};

const RAGChip = ({ ragStatus }) => {
  const classes = useStyles();
  const defineClass = `rag${getRAG(ragStatus)}`;
  return (
    <Chip
      size="small"
      label=""
      className={`${classes.ragChip} ${classes[defineClass]}`}
    />
  );
};

Upvotes: 2

Related Questions