Home > OS >  How can I make the Material UI Chip component not to be displayed when there is no content inside?
How can I make the Material UI Chip component not to be displayed when there is no content inside?

Time:11-04

I am creating an app that will display some content from an Api. I have created a Material UI Card component to present the information I get and within that card, I have a mui Chip component.

<Card sx={{ width: "368px" }}>
      <CardActionArea>
        <CardMedia component="img" height="200" image={image} />
        <CardContent>
          <Box sx={{ display: "flex", alignItems: "center" }}>
            <Typography variant="subtitle2" color="#1976d2">
              {center}
              <FiberManualRecordIcon sx={{ fontSize: 4 }} />
            </Typography>
            <Typography variant="subtitle2" color="#1976d2">
              {date}
            </Typography>
          </Box>
          <Typography variant="h5" component="div">
            {title}
          </Typography>
          <Typography
            sx={{
              display: "-webkit-box",
              overflow: "hidden",
              textOverflow: "ellipsis",
            }}
            variant="body2"
          >
            {description}
          </Typography>
          <Box />
          <Box>
            <Chip label={keywords} />
          </Box>
        </CardContent>
      </CardActionArea>
    </Card>

The labels of the Chip component are some keywords,which I get them from an Api response. But sometimes there are no keywords. In that case, I want the mui Chip component not to be displayed at all, instead of getting one with empty content. Is there a way to make it happen?

CodePudding user response:

Please try this.

<Card sx={{ width: "368px" }}>
      <CardActionArea>
        <CardMedia component="img" height="200" image={image} />
        <CardContent>
          <Box sx={{ display: "flex", alignItems: "center" }}>
            <Typography variant="subtitle2" color="#1976d2">
              {center}
              <FiberManualRecordIcon sx={{ fontSize: 4 }} />
            </Typography>
            <Typography variant="subtitle2" color="#1976d2">
              {date}
            </Typography>
          </Box>
          <Typography variant="h5" component="div">
            {title}
          </Typography>
          <Typography
            sx={{
              display: "-webkit-box",
              overflow: "hidden",
              textOverflow: "ellipsis",
            }}
            variant="body2"
          >
            {description}
          </Typography>
          <Box />
          <Box>
           {keywords && ( <Chip label={keywords} />)}
          </Box>
        </CardContent>
      </CardActionArea>
    </Card>
  • Related