Material-UI Styled API: classes not applying to child elements

Viewed 208

I'm trying to create a page in Material-UI v5. I'm familiar with v4, getting better with v5. But for some reason the css styles aren't applying here.

Neither my testcss or loadingBox classes have any effect.

Why are they not working? Is there something fundamental I'm missing here?

import React, {useEffect, useState} from 'react';
import {
    Avatar, Box, CircularProgress, Fade,
    IconButton,
    Paper, SpeedDial, SpeedDialAction,
    styled, Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TableRow
} from "@mui/material";


const PREFIX = 'PageUsers';
const classes = {
    errorBox: `${PREFIX}-errorBox`,
    loadingBox: `${PREFIX}-loadingBox`,
    testcss: `${PREFIX}-testcss`,
};

const StyledFullPageLayout = styled(FullPageLayout)(({theme}: any) => ({
    [`&.${classes.errorBox}`]: {
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'middle',
    },
    [`&.${classes.loadingBox}`]: {
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'middle',
    },
    [`&.${classes.testcss}`]: {
        background: 'rgba(255,0,0,0.2)',
    },
}));

function PageWGPeers(props: any) {
    const [loading, setLoading] = useState<boolean>(true);
    const [error, setError] = useState<boolean>(false);

    return (
        <StyledFullPageLayout
            title={'Users'}
            className={classes.testcss}
        >
            <Fade in={loading}><Box className={classes.loadingBox}><CircularProgress /></Box></Fade>
            <Fade in={!loading && error} unmountOnExit><div>Error</div></Fade>
            <Fade in={!loading && !error && peers.length === 0} unmountOnExit><div>Empty</div></Fade>
            <Fade in={!loading && !error && peers.length > 0} unmountOnExit>Loaded</Fade>
        </StyledFullPageLayout>
    );

}
1 Answers

testcss class name works fine, you can apply a background-color to see it more clearly. You are passing the loadingBox class name to the descendant of the StyledFullPageLayout component so you have to use this selector:

'& className'

So change your code to:

// Notice I add a space after the '&'
[`& .${classes.loadingBox}`]: {
  display: 'flex',
  justifyContent: 'center',
  alignItems: 'middle',
},

Codesandbox Demo

Related