Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dynamically change property value in an object in Material UI?

I have property named listItem in useStyles defined outside of TodoListItem like this:

const useStyles = makeStyles(theme => ({
        listItem: {
            textDecoration: 'none'
        }
    })
)

const TodoListItem({checked}) => {
    const classes = useStyles();
    return <ListItemText className={classes.listItem} primary={text}/>
};

Then I wanted to change the status of textDecoration based on variable named checked. And I tried to directly use checked variable in useStyles but does not work as it is out of scope.

textDecoration: checked ? 'line-through' : 'none'

In this case, how should I pass checked variable into useStyles to make the ternary operator working?

like image 653
D Park Avatar asked Dec 07 '22 10:12

D Park


1 Answers

CSS properties in makeStyles support custom props for dynamic styling:

const useStyles = makeStyles(theme => ({
    listItem: {
        textDecoration: ({checked}) => checked ? 'line-through' : 'none'
    }
}));

const Component = props => {
    const classes = useStyles({checked: props.checked});
    
    ...
}
like image 187
Remolten Avatar answered Dec 31 '22 01:12

Remolten