Skip to content
Advertisement

how to use state value in makeStyles in materail ui react

I am creating a Webpage. I am using Material UI for Components. Here’s the Code:

import {  makeStyles, Typography } from "@material-ui/core";
const useStyles = makeStyles((theme) => ({

    container: {
        backgroundColor: "white", display: displayStyle
    },

}));
export default function HomePage() {
    const classes = useStyles();

    const [displayStyle, setDisplayStyle] = useState("flex")

    return (
        <>
            <div>My Page</div>
            <div className={classes.container}>
                <div >
                    <Typography  >
                        Our Orders
                    </Typography>
                </div>
            </div>
        </>
    );
}

I have a state named displayStyle . I want to use this state value in makeStyles. But it shows displayStyle is undefined because it is inside the Function. How to make it use in makeStyles. I want to set Styles based on the state value. Please help me with some solutions

Advertisement

Answer

state is available in the component. So you need to move useStyles into your component to access the displayStyle:

import {  makeStyles, Typography } from "@material-ui/core";
export default function HomePage() {
    const [displayStyle, setDisplayStyle] = useState("flex")
    
    const useStyles = makeStyles((theme) => ({
        container: {
            backgroundColor: "white", display: displayStyle
        },
    }));
    const classes = useStyles();

   
    return (
        <>
            <div>My Page</div>
            <div className={classes.container}>
                <div >
                    <Typography  >
                        Our Orders
                    </Typography>
                </div>
            </div>
        </>
    );
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement