Search code examples
javascriptreactjsconditional-operatorconditional-rendering

Double conditional rendering in react?


I'm building a small clothing store app in React, just to learn things. I implemented a filter by price section but I would want to be able to write a condition for the case in which there's no item in the selected price range, instead of the page being blank.

render() {
        const filteredOpt2 = this.state.items.filter(item => item.price <= 60);
        const filteredOpt3 = this.state.items.filter(item => item.price >= 60 && item.price <= 100);
        
        return (
              <div>
                    {
                         this.state.selectedOption === "option1"
                         ? <ProductList products={this.state.items} style={{marginLeft: 0}}/>
                         : this.state.selectedOption === "option2"
                         ? <ProductList products={filteredOpt2} style={{marginLeft: 0}}/>
                         : this.state.selectedOption === "option3"
                         ? <ProductList products={filteredOpt3} style={{marginLeft: 0}}/>
                         : null
                    }
              </div>
        )
}

I know the code is very repetitive and really not ideal, but I couldn't come up with a better approach for now.

So what I wish to do, is, let's say the filteredOpt2 results in an empty array, how and where could I implement a condition that says if this happens, display a p tag showing a text?


Solution

  • You are sending the product list down to ProductList component via props. In that component, where you use your props.products, you can add something like this:

    {!props.products.length
      ? <p>No product matched the criteria</p> 
      : props.products.map(product => {... whatever your code is })
    }
    

    To elaborate, if the products.length is zero, you show your 'no product' text, otherwise, show the products.