Material-ui: Set tab background color based on passed prop to a styledTab

Viewed 18

I have prepared this custom tab to style it as I want:

import { withStyles } from "@material-ui/core/styles";

const StyledTab = withStyles((theme) => ({
  root: {
    backgroundColor: "yellow",
  },
}))((props) => {
  const { shouldSetBackgroundColorToOrange } = props;
  return <Tab {...props} />;
});

This is how it's used:

<StyledTab label={"Room"} shouldSetBackgroundColorToOrange={true} />;

I'd like to set its color to orange based on the shouldSetBackgroundColorToOrange prop that's passed to it.

But, I couldn't find a way to do this.

1 Answers

Have a look at the code below and in this working codesandbox

In using the button but you can easily adopt it in your code

import React from "react";
import { createStyles, makeStyles } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";

interface styleProps {
  shouldSetBackgroundColorToOrange: boolean;
}

const useStyles = makeStyles((theme) =>
  createStyles({
    root: {
      backgroundColor: ({shouldSetBackgroundColorToOrange}: styleProps) =>
        shouldSetBackgroundColorToOrange ? "orange" : "yellow"
    }
  })
);

function TestComponent() {
  const classes = useStyles({ shouldSetBackgroundColorToOrange: true });
  return (
    <Button variant="contained" className={classes.root}>
     Button
    </Button>
  );
}

export default TestComponent;
Related