Home > Enterprise >  Unable to increase the counter to the Badge in React Typescript
Unable to increase the counter to the Badge in React Typescript

Time:11-04

I am not sure where to apply the count to my Badge Component. The displayValue should have the count but I am not sure how to apply it.

EDITED : Counter is applied now but when I decrement the counter , after 0 , it should disappear. I have the logic for this and it works only when I apply badgeContent ="0" in App.tsx and not when the badge is 0 by clicking the decrement button.

I tried it on codesandbox. Here is the link. Please help. Thanks!

https://codesandbox.io/s/badgecomponent-ljdq25?file=/src/components/Badge.tsx:468-480

CodePudding user response:

Your count is incrementing, but it's not wired up to anything. If you change your code to use count your state will update. So change

{Number(badgeContent) > 0 && (
   <span className={`badgeContent`}>{displayValue}</span>
)}

to:

{Number(badgeContent) > 0 && (
   <span className={`badgeContent`}>{count}</span>
)}

CodePudding user response:

I see badgeContent is string so I added it to the state and converted it to the number const [count, setCount] = useState( badgeContent);

and controlling count in the event listener as:

  const incrementBadge = () => {
    console.log("Badge Clicked");
    setCount(count   1);
  };

And showing the badge in UI as:

  <span className="badge">
    <span className={`badgeText`}>Badge</span>
    {count > 0 && count <= max ? (
      <span className={`badgeContent`}>{count}</span>
    ) : (
      <span className={`badgeContent`}>{`99 `}</span>
    )}
    {count === 0 && showZero ? (
      <span className={`badgeContent`}>{count}</span>
    ) : (
      ""
    )}
  </span>

Please check out the full codes on codesandbox

  • Related