Change component prop through css hover in react-materialui

Viewed 243

I am trying to change the noWrap property of a Typography element upon hover. I have declared a custom CSS class for the parent element and the hover does work. But I have no idea how to alter the noWrap property through CSS now.

I have tried this (the hover works):

const useStyles = makeStyles((theme) => ({
    paper: {
      padding: theme.spacing(2),
      "&:hover .questionText": {
        noWrap: true
      }
    }
}));

And my JSX:

return(
<Paper className={classes.paper}>
 <Typography className="questionText" noWrap={false} gutterBottom variant="body2">test</Typography>
</Paper>);

Thanks for your help

3 Answers

I'd toggle the boolean flag for your noWrap attribute via setState (or state hooks) using a js mouseover. Something like -

const [ wrap, setWrap ] = useState(false);

function toggleWrap() {
  setWrap(!wrap);
}

return(
  <Paper ...>
    <Typography noWrap={wrap} onMouseOver={()=>toggleWrap()} ... />
  </Paper>
);

Setting noWrap={true} props in Typography will apply white-space: nowrap styles to your component. This is how you do it using jss:

const useStyles = makeStyles((theme) => ({
    paper: {
      padding: theme.spacing(2),
      "&:hover .questionText": {
        whiteSpace: "nowrap",
      }
    }
}));

Live Demo

Edit 66968582/change-component-prop-through-css-hover-in-react-materialui

Thanks to Ozrix, I have solved my problem with the following:

const [wrap, setWrap] = useState(false);

and

<Paper className={classes.paper} onMouseEnter={() => {setWrap(true)}} onMouseLeave={() => {setWrap(false)}}>
 <Typography noWrap={wrap} gutterBottom variant="body2">
</Paper>
Related