Rahil Əliyev
Rahil Əliyev

Reputation: 309

How can I do dynamic badge on React CoreUI?

I have a problem with a badge on Core UI. I have a Sidebar and one of the elements is Chat. When a new message comes, the badge must show new message. But the old developer have written different ways and I can not change it. I cannot find anything for this.

My codes Sidebar elements

const _nav = [
  {
    _tag: "CSidebarNavItem",
    name: "Chat",
    to: "/chat",
    filter: "feedbacks",
    icon: "cil-speech",
    badge: {
      color: "info",
      text: "NEW MESSAGE",
    },
  },
]

My React component

  import navigation from "./_nav";
  const [filteredNav, setFilteredNav] = useState([]);
  const [chatBadge, setChatBadge] = useState(false);

  const handleChatBadge = () => {
     setChatBadge(true)
  }

   // it is a sidebar element for user-role
   useLayoutEffect(() => {
    allwedMenu().then((res) => {
      const arr = [navigation[0]];
      res.data.items.forEach((element) => {
        arr.push(element.name);
      });
      setFilteredNav(navigation.filter((item) => arr.includes(item.filter)));
    });
  }, []);

  <CSidebarNav>
   <CCreateElement
              items={filteredNav}
              components={{
                CSidebarNavDivider,
                CSidebarNavDropdown,
                CSidebarNavItem,
                CSidebarNavTitle,
              }}
            />
    </CSidebarNav>

I need the badge to show when chatBadge is true. But I don't know how can I write this.

Upvotes: 2

Views: 320

Answers (1)

user21014068
user21014068

Reputation: 36

You can only add a condition to show the badge when chatBadge is true. Based on the Value of ChatBadge, you can use the property of the Component CSideBarNavItem to display the badge and pass the colour and text properties.

Here's the correct code:

<CSidebarNav>
  <CCreateElement
    items={filteredNav}
    components={{
      CSidebarNavDivider,
      CSidebarNavDropdown,
      CSidebarNavItem,
      CSidebarNavTitle,
    }}
  />
  {filteredNav.map((item, index) => (
    <CSidebarNavItem
      key={index}
      name={item.name}
      to={item.to}
      icon={item.icon}
      badge={
        item.name === "Chat" && chatBadge
          ? { color: "info", text: "NEW MESSAGE" }
          : null
      }
    />
  ))}
</CSidebarNav>

Hope it helps.

Upvotes: 0

Related Questions