Home > front end >  Conditionally rendered list in React is behaving with one method, but not another
Conditionally rendered list in React is behaving with one method, but not another

Time:05-22

I've got a list of products to render. I also have an array of keywords that are used to exclude products from being rendered.

I am looping over the array of keywords and checking if the product title contains any of the entries. It then returns a boolean.

The following code does not work. The console.log works and reflects the result but nothing is rendered.

function inExcludes(product, excludedItems) {

  excludedItems.forEach( item => {
    if (product.includes(item)) {
      console.log(true);
      return true;
    } else {
      console.log(false);
      return false;
    }
  })
  
}
export function CardsFiltered(props) {

  const cards = props.items.map((product) => {
    if (inExcludes(product.title, props.excludedItems) === false)
    return (
      <CardValidation
        key={product.id}
        id={product.id}
        product={product}
      />
    )
  })

  return (
    <>
      {cards}
    </>
  );

}

But if I set a variable as a boolean, switch that variable if the condition is true, and then return that variable, it works and my cards are rendered (code below).

Is anyone able to shed light on this? Because I can't figure it out.

function inExcludes(product, excludedItems) {
  let result = false;

  excludedItems.forEach( item => {
    if (product.includes(item)) {
      result = true;
    }
  })

  return result;
}
export function CardsFiltered(props) {

  const cards = props.items.map((product) => {
    if (!inExcludes(product.title, props.excludedItems))
    return (
      <CardValidation
        key={product.id}
        id={product.id}
        product={product}
      />
    )
  })

  return (
    <>
      {cards}
    </>
  );

}

CodePudding user response:

Your first implementation of 'inExcludes' isn't returning a boolean (true/false). It's just executing the 'forEach' on each item in the excludedItems array. The return within that loop doesn't return from the function as a whole.

So, as it effectively returns 'undefined' your render decides not to render anything.

Here's something that does what you're after (simplified a bit):

https://codesandbox.io/s/awesome-mcclintock-hkkhsi?file=/src/App.js

  • Related