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
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>
</>
);
}
One Solution is to move makeStyles in the component and if you don't want to move it in the component then you can try this hack
import { makeStyles, Typography } from "@material-ui/core";
let style;
const useStyles = makeStyles((theme) => ({
container: {
backgroundColor: "white", display: style
},
}));
export default function HomePage() {
const [displayStyle, setDisplayStyle] = useState("flex")
style = displayStyle;
const classes = useStyles();
return (
<>
<div>My Page</div>
<div className={classes.container}>
<div >
<Typography >
Our Orders
</Typography>
</div>
</div>
</>
);
}
Just simply make the displayStyle available to useStyle function by defining the state in the useStyle function.
Move this line inside the useStyle function.
const [displayStyle, setDisplayStyle] = useState("flex");
So our component looks like this
import { makeStyles, Typography } from "@material-ui/core";
const useStyles = makeStyles((theme) => ({
const [displayStyle, setDisplayStyle] = useState("flex")
container: {
backgroundColor: "white", display: displayStyle
},
}));
export default function HomePage() {
const classes = useStyles();
return (
<>
<div>My Page</div>
<div className={classes.container}>
<div >
<Typography >
Our Orders
</Typography>
</div>
</div>
</>
);
}