0
votes

EDIT: after further testing it seems that each time the component is re-rendered material-ui's makeStyles is executed again, while JSS's createUseStyles is NOT!

I have a component that has to dynamically change the styling based on the state. When I use makeStyles provided with material-ui the code works perfectly:

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

const useStyles = makeStyles(theme => ({
  root: {
    position: "relative",
    borderRadius: filteredItems.length > 0 ? "4px 4px 0 0" : "4px 4px 4px 4px", // this is the relevant line
    backgroundColor: "white",
    color: "black",
  },
}));

But I don't want to use material-ui, I just want to use JSS. Unfortunately it doesn't work. It looks like filteredItems.length > 0 always returns false, so I guess that createUseStyles for some reason is executed differently than makeStyles:

import { createUseStyles } from "react-jss";

const useStyles = createUseStyles(theme => ({
  root: {
    position: "relative",
    borderRadius: filteredItems.length > 0 ? "4px 4px 0 0" : "4px 4px 4px 4px", // this is the relevant line
    backgroundColor: "white",
    color: "black",
  },
}));

I know that material-ui runs under the hood JSS so I'm puzzled by this behaviour. I thought about adding two CSS classes and toggle them within my JSX, but I think sorting out the issue in the styling is the cleanest solution here. Anyone knows why this is happening or how to fix the issue?

EDIT2: To fix the issue I simply created two classes and toggled them within JSX:

const useStyles = createUseStyles(() => {
  return ({
    root: {
      position: "relative",
      borderRadius: "4px 4px 4px 4px",
      backgroundColor: "white",
      color: "black",
    },
    withItems: {
      borderRadius: "4px 4px 0 0",
    },
  })
});

And then:

<div className={filteredItems.length > 0 ? `${classes.root} ${classes.withItems}` : classes.root}>
1

1 Answers

0
votes

Have you tried this approach?

const useStyles = makeStyles({
  root: {
    position: "relative",
    backgroundColor: "white",
    color: "black",
    borderRadius: props.withItems ? "4px 4px 0 0" : "4px 4px 4px 4px",
    // or
    // borderRadius: "4px 4px 4px 4px",
    // borderRadius: props.withItems && "4px 4px 0 0",
    color: props => props.color,
  },
});


render() {
  const classes = useStyles({ withItems: filteredItems.length > 0 });

  return <div className={classes.root} />;
}