0

In my React app, I have a component which takes in some data. Depending on the value of that data, I want to show the component with a different coloured background.

The styles are defined as:

const useStyles = makeStyles((theme) => ({
  class1: {
    backgroundColor: "red",
  },
  class2: {
    backgroundColor: "pink",
  },
}));

The component is:

const MyBox = ({ data }) => {
  let classes = useStyles();

  let innerClassName;

  if (data.value) {
    innerClassName = "class1";
  } else {
    innerClassName = "class2";
  }

  return (
    <div className={innerClassName}>
Content goes here
    </div>
  );
};

export default MyBox;

However, this gives the component a class of "class1" or "class2", which doesn't get picked up by makeStyles. I also tried <div className={classes.innerClassName}> but then it looks for a class called 'innerClassName' which obviously it can't find.

I think I need to use some kind of variable string within <div className={????}> but I've tried various template literal strings and none of them have worked. What should I be doing?

Sharon
  • 3,471
  • 13
  • 60
  • 93
  • 1
    Insteasd of `className={classes.innerClassName}`, maybe you can try `className={classes[innerClassName]}>`. I believe the square brackets will help with dynamic interpretation of object attribute in JS – Bao Huynh Lam Feb 23 '22 at 13:59

0 Answers0