joekevinrayan96
joekevinrayan96

Reputation: 634

Conditionally applying css not working in React JS using Typescript

I have the following code whereas onclick I should make the Box stay highlighted with the black border.

interface BigButtonProps {


onClick(): void;
  Title: string;
  Description?: string;
  startIcon?: React.ElementType;
}

const BigButton: FC<BigButtonProps> = (props: BigButtonProps, { active }) => {
  const [isClicked, setClicked] = useState(false);
  const clickMe = () => {
    setClicked(!isClicked);
    console.log("say hello");
  };
  const SvgIconStyles: CSS.Properties = {
    display: "block",
  };
  const BoxStyles: CSS.Properties = {
    border: "1.5px solid black",
  };

  const BoxStylesActive: CSS.Properties = {
    border: "1.5px solid black",
  };
  return (
    <Box
      sx={{
        height: {
          xs: "45px",
          md: "100px",
        },
        width: {
          xs: "45px",
          md: "300px",
        },
    borderRadius: "10px",

    boxShadow: "0 2px 3px 2px rgba(0, 0, 0, .125)",
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    flexDirection: "column",
    ":hover": {
      border: "1.5px solid blue",
    },
  }}
  className={classNames("BoxStyles", { BoxStylesActive: isClicked })}
  onClick={() => {
    clickMe();
  }}
>
  <Typography variant="h1">{props.Title}</Typography>

  <Typography variant="subtitle1">{props.Description}</Typography>
  <SvgIcon
    component={CheckCircleIcon}
    sx={{
      display: "block",
    }}
  />
</Box>


);
};

export default BigButton;

When I click on the button it should change the border color to solid black. When I do CSS active it does change on click but doesn't remain changed to black. So I have to apply CSS conditionally so I did create the CSS methods with the property type CSS.Properties; I'm using typescript and this is a react component I'm working on with. I'm not really sure what am I doing wrong here?

Upvotes: 1

Views: 818

Answers (1)

Sir hennihau
Sir hennihau

Reputation: 1794

You can try something like

<Box styles={isClicked ? BoxStylesActive : BoxStyles}>
// ...

Notice that BoxStylesActive and BoxStyles are the same in your pasted code. So don't be surprised if you see no changes.

<Box sx={{border: isClicked ? "1.5px solid black" : none}}>
// ...

This can be used alternatively.

You are mixing sx prop and styles here. Also your BoxStylesActive is an object and no css class. So using classNames() won't have an effect on it.

Upvotes: 2

Related Questions