Search code examples
reactjsmaterial-uireactn

Material-UI Set Class Property From State


I have a component like below. I want to be able to use a value from the state such as [opacity, setOpacity] = useGlobal('opacity') and have the opacity be the value for tileBody background. What would be the best way to go about this?

import React from 'react';
import clsx from 'clsx';
import { makeStyles } from '@material-ui/core/styles';
import Typography from '@material-ui/core/Typography';
import Grid from '@material-ui/core/Grid';
import {CardContent, fade, Hidden} from "@material-ui/core";
import Card from "@material-ui/core/Card";
import { useGlobal, setGlobal, useDispatch } from 'reactn';

/*
options = {
    ...other options,
    tileTransparencyValue: 75,
*/


const useStyles = makeStyles(theme => ({
    tile: {
        backgroundColor: 'transparent',
    },
    tileHeader:  {
        backgroundColor: fade(theme.palette.grey[800], 0.7),
    },
    tileBody: {
        backgroundColor: fade(theme.palette.grey[800], tileTransparencyValue/100),
    },
}));


export default function DashTile(props) {
    const [options, setOptions] = useGlobal('options');
    const {title, content} = props;
    const classes = useStyles();

    return (
        <Grid item lg={4} xs={12}>
            <Card className={classes.tile}>
                <CardContent className={classes.tileHeader}>
                    <Typography variant="h5">{title}</Typography>
                </CardContent>
                <CardContent className={classes.tileBody}>
                    <Typography variant="content">{content}</Typography>
                </CardContent>
            </Card>
        </Grid>
    );
}

Solution

  • You can pass props to your styles like this:

    export default function DashTile(props) {
        const [options, setOptions] = useGlobal('options');
        const [opacity, setOpacity] = useGlobal('opacity')
        const {title, content} = props;
        const classes = useStyles({opacity})
    
        return (
            <Grid item lg={4} xs={12}>
                <Card className={classes.tile}>
                    <CardContent className={classes.tileHeader}>
                        <Typography variant="h5">{title}</Typography>
                    </CardContent>
                    <CardContent className={classes.tileBody}>
                        <Typography variant="content">{content}</Typography>
                    </CardContent>
                </Card>
            </Grid>
        );
    }
    

    Then you can retrive the props inside the styles like this:

    const useStyles = makeStyles(theme => ({
        tile: {
            backgroundColor: 'transparent',
        },
        tileHeader:  {
            backgroundColor: fade(theme.palette.grey[800], 0.7),
        },
        tileBody: {
            backgroundColor: ({opacity}) => fade(theme.palette.grey[800], opacity)
        },
    }));
    

    Reference: makeStyles