Home > Net >  React how not to display if doing calculation inside jsx
React how not to display if doing calculation inside jsx

Time:06-19

I am inside a map, and I am calulating how many items exist for each category.

I am then setting its value to a property. This works fine. The issue is it also shows that value on the screen, which I don't want.

               {
                  (tab.itemCount = props.items.filter(
                    (item) => item.category === tab.category
                  ).length)
                }

How can I do this calculation inside the JSX without it also showing the length value on the screen?

CodePudding user response:

The best approach would be to put this logic not directly inside the JSX, but at the point where tab.itemCount is used. Perhaps at the top level of the component, or directly inside the render method if you're using a class component?

(Though, assigning to tab.itemCount in the first place also sounds like a mistake, because that would be a mutation of the tab object, and mutation of state and props should always be avoided in React, else you'll often run into problems)

If you really had to do something like this - which I'd highly recommend against - you could use the comma operator, or an IIFE that doesn't return anything.

{
    (() => {
        tab.itemCount = props.items.filter(
            (item) => item.category === tab.category
        ).length);
    })()
}
  • Related