Reputation: 514
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?
Upvotes: 6
Views: 4578
Reputation: 2682
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});
...
}
Upvotes: 11
Reputation: 15146
You can pass props
, state
, and whatever you want as a param to the style hook.
And it has better readability since we can understand whether the style hook is using other params or not quickly.
const useStyles = checked =>
makeStyles(theme => ({
listItem: {
textDecoration: checked ? 'line-through' : 'none'
}
}));
const classes = useStyles(checked)();
Upvotes: 4
Reputation: 2877
I think that the most easy way to achieve it is to use style
instead classname
and manipulate everything that will use logic outside big style object
<ListItemText style={[classes.listItem,{textDecoration: checked ? 'line-through' : 'none'}]} primary={text}/>
Upvotes: 2