Search code examples
cssreactjscss-selectorsreact-css-modules

React- Conditionally applying css in div but it does not work


Have looked at other examples and trying to do the same thing but not sure why my code is not working. I have code which loops through some keys and renders a div. I want to conditionally apply some styles based on whether the key is even or odd. Example:

<div className={parseInt(key) % 2 === 0  ? 'label1' : 'label2' }>
     <span style={{ marginLeft: "10px" }}>{key}:00</span>
</div>
           

The styles are accessible in the same file and look something like:

# Material UI 
const useStyles = makeStyles((theme) => ({
  label1: {
    width: "50px",
    height: "16px",
    top: "458px",
    background: "yellow",
    fontSize: "12px",
  },
  label2: {
    width: "50px",
    height: "16px",
    top: "458px",
    background: "red",
    fontSize: "12px",
  }, 
}));

What am I doing wrong? Currently no style is getting applied to the div


Solution

  • You need to use the classes from the material ui useStyles hook.

    const classes = useStyles()
    
    ....
    
    <div className={parseInt(key) % 2 === 0  ? classes.label1 : classes.label2 }>
         <span style={{ marginLeft: "10px" }}>{key}:00</span>
    </div>
    

    Check the useStyles hook api: https://material-ui.com/styles/basics/

    If you have a class component and you can use hooks then you can do it with the withStyles higher order component, like this example:

    import { withStyles } from "@material-ui/core/styles"
    
    const styles = theme => ({
      label1: {
        backgroundColor: "red",
      },
      label2: {
        backgroundColor: "red",
      },
    })
    
    class ClassComponent extends Component {
      state = {
        searchNodes: "",
      }
    
      render() {
        const { classes } = this.props
        return (
          <div className={parseInt(key) % 2 === 0 ? classes.label1 : classes.label2}>
            <span style={{ marginLeft: "10px" }}>{key}:00</span>
          </div>
        )
      }
    }
    
    export default withStyles(styles, { withTheme: true })(ClassComponent)