0

Guys look at the screen shot. I am building a chat window to show unread messages. Though it works fine. code window

and the output window

I just can't figure out a simple condition when the count is 0 I want to hide the entire badge.

 <Badge
                                  badgeContent={jobcard.jobcard_count.map(
                                    (row2) => {
                                      if (row2.jobcard_id === row._id)
                                        return row2.count;
                                    }
                                  )}
                                  color="primary"
                                >
                                  <MailIcon />
                                </Badge>

2 Answers2

1

Try conditional rendering with short circuit evaluation, rather than doing the row2.count logic inside the badgeContent, move it out of the Badge Component and return a Badge Component only if row2.count is greater than 0.

{
    jobcard.jobcard_count.map(
      (row2) => {
        if (row2.jobcard_id === row._id)
          row2.count > 0 && <Badge badgeContent={row2.count} color="primary"><MailIcon /></Badge>;
      }
  )
}
yondu_udanta
  • 797
  • 1
  • 6
  • 13
  • how can row2.count be evalueted before? its param in map()? yet tested and as i thought it didn't work – Sabyasachi Rout Jun 18 '21 at 14:48
  • hey, yeah you are right, I assumed row2 was available in the outer scope. Could you share the entire code where you are using 'row' as the looping variable? – yondu_udanta Jun 18 '21 at 14:52
  • can I know your mail id or something like that to share code? code is bit long so this doesn't allow to paste – Sabyasachi Rout Jun 19 '21 at 14:04
  • You could use a pasting service like pastebin or sth and post the link here. – yondu_udanta Jun 19 '21 at 14:35
  • @SabyasachiRout I edited the answer after checking your code. The major change is, rather than doing the row2.count logic inside the badgeContent, move it out of the Badge Component and return a Badge Component only if row2.count is greater than 0. – yondu_udanta Jun 21 '21 at 07:09
0

You could hide the entire badge if the count is 0, using an if-statement. In the else-part you should put the MailIcon.

Alternatively, you could add a class if the count is 0, which hides the badge using CSS.

Joel'-'
  • 652
  • 1
  • 5
  • 17