Home > Software engineering >  MUI CardContent and flexBox doesn't work with typography and chip
MUI CardContent and flexBox doesn't work with typography and chip

Time:09-09

Below is react code made with MUI. The aim is to create a Card that displays Character Information.

const CharacterPreview = ({ characterKey }: CharacterPreviewProps) => {
  return (
    <Card sx={{ maxWidth: 256, borderRadius: 4 }}>
      <Box
        component="a"
        href={`/#/${characterKey}`}
        display="flex"
        position="relative"
        sx={{
          "&::before": {
            content: '""',
            display: "block",
            position: "absolute",
            left: 0,
            top: 0,
            width: "100%",
            height: "100%",
            opacity: 0.7,
            backgroundImage: `url(${bannerImgUrl})`,
            backgroundPosition: "center",
            backgroundSize: "cover",
          },
        }}
        width="100%"
      >
        <Box
          flexShrink={1}
          sx={{ maxWidth: { xs: "40%", lg: "40%" } }}
          alignSelf="flex-end"
          display="flex"
          flexDirection="column"
          zIndex={1}
        >
          <Box
            component="img"
            src={iconImgUrl}
            width="100%"
            height="auto"
            maxWidth={256}
            sx={{ mt: "auto" }}
          />
        </Box>
      </Box>
      <CardContent>
        <Typography variant="h5" component="div">
          {characterName}
        </Typography>
        {/* <Typography variant="body2" color="text.secondary"> */}
        {/*   {characterInfo.title as string} */}
        {/* </Typography> */}
        <Chip
          label={characterChipInfo}
          size="small"
        />
      </CardContent>
    </Card>
  );
};

This is what the final result looks like:

Result I got

I want the chip component (reads as CRYO in the image and is characterChipInfo in the above code) to be on the same line as the characterName and be separated like a space-between flexbox, however using the Box component with flex-box and justifyContent="space-between" to encase the name Typography and Chip doesn't work. I've also tried along with it changing the Typography display to inline-flex and inline-block, which makes them on the same line but the Box's justifyContent=space-between doesn't work.

CodePudding user response:

You need to use a Stack component of Material UI like so: CodeSandBox

    <Stack
      direction="row"
      spacing={2}
      justifyContent="space-between"
      alignItems="center"
    >
        <Typography variant="h5" component="div">
          {characterName}
        </Typography>
        {/* <Typography variant="body2" color="text.secondary"> */}
        {/*   {characterInfo.title as string} */}
        {/* </Typography> */}
        <Chip
          label={characterChipInfo}
          size="small"
        />
    </Stack>
  • Related