Home > Back-end >  No items being rendered when the page reloads - trying to implement a search bar
No items being rendered when the page reloads - trying to implement a search bar

Time:06-24

I am trying to implement a search bar and I am going to attach the code for it below. The issue is that when the page reloads and the search bar is empty, no products end up getting render but as soon I start typing something in the search bar, the items start to render as per the search key.

Can anyone assist me with this please?

          .filter((val) => {
            if (props.searchTerm == "") {
              return val;
            } else if (
              val.additionalInfo.toLowerCase().includes(props.searchTerm)
            ) {
              return val;
            }
          })
          .map((post) => {
            return (
              <div className="product-metainfo col-2 mb-4">
                <img src={post.images[0].src}></img>
                <h3 className="product-brand">{post.brand}</h3>
                <h4 className="product-product">{post.additionalInfo}</h4>
                <div className="product-price">
                  <span>
                    <span className="discounted-price">Rs. {post.price} </span>
                    <span className="product-strike"> Rs. {post.mrp}</span>
                  </span>
                  <span className="product-discountPercentage">
                    ({Math.floor((100 * post.discount) / post.mrp)}% off)
                  </span>
                </div>
              </div>
            );
          })}

CodePudding user response:

Did you set the default state for searchTerm as undefined or null? In this case you need to set the default state for searchTerm as empty string to make it work.

  • Related