I’m currently working on a React project where I’ve been using Material-UI’s makeStyles() function for styling my components. However, I recently learned that makeStyles() is not compatible with React 18’s concurrent mode.
I’m looking for an alternative feature in Material-UI that provides similar functionality to makeStyles(), but is compatible with React 18. Ideally, this feature would allow me to define styles in a similar way to makeStyles(), and would also allow me to access theme values directly.
Here’s an example of how I’m currently using makeStyles():
const useStyles = makeStyles((theme) => ({
root: {
marginLeft: theme.spacing(1),
},
}));
const App = () => {
const classes = useStyles();
return <Typography className={classes.root}>{data.title}</Typography>;
}
Can anyone suggest a suitable replacement for makeStyles() that works with React 18?
I’ve been using inline styles and the makeStyles() function from Material-UI to style my components in my React application.I was expecting to continue using makeStyles() and inline styles for my styling needs. However, I recently learned that makeStyles() is not compatible with React 18’s concurrent mode, which I plan to use in my project.
>Solution :
In Material-UI v5, you can use the sx prop or the styled function from @mui/system as alternatives to makeStyles(). Both are compatible with React 18.
The sx prop is a shorthand for all style props. It allows you to specify values from the theme. Here’s an example of how you can use the sx prop:
<Typography
variant="subtitle1"
gutterBottom
sx={{ marginLeft: (theme) => theme.spacing(1) }}
>
{data?.title}
</Typography>
The styled function from @mui/system allows you to create styled components. It also allows you to access theme values directly. Here’s an example:
import { styled } from '@mui/system';
import { Typography } from '@mui/material';
const StyledTypography = styled(Typography)(({ theme }) => ({
marginLeft: theme.spacing(1),
}));
const App = () => {
return <StyledTypography variant="subtitle1" gutterBottom>{data?.title}</StyledTypography>;
}
Note: sx attribute is only valid to the Material UI components like Grid, Typography, but the styled from @mui/system can be used with both HTML tags and Material UI components