0

I have products in JSON format that are fetched and shown in the frontend. In my products.json there is an image URL for each products, but only some have image URLs in them, others are empty. When I am looping the data in react I always get error in my react app saying Cannot read property of null in the <img/> tag, how do I write a logic that only renders the image when there is an image source else just return an empty div?

<ul>
          {this.state.items.map((items, index) => {
            return (
              <li className="ProductList-product" key={items.id}>
                  <h3>{items.title}</h3>
                  <p>{items.description}</p>
                  <div className="price-box">    
                  <p>from: {items.price} $</p>
                  </div>
                  <div>
                  {<img src={items.photo} alt=""/>}
                  {/* {console.log(items.photo.id)} */}
                  </div>
              </li>
                
            );
          })}
        </ul>
1
  • 1
    The practice is for the child item within the loop to be singular. In your case items=>item Commented Jan 9, 2021 at 10:30

2 Answers 2

1

replace your

{<img src={items.photo} alt=""/>}

with

{items.photo && <img src={items.photo} alt=""/>}

it will only render img element when item.photo is not null.

Sign up to request clarification or add additional context in comments.

Comments

1

You can set a condition. For example:

  <ul>
      {this.state.items.map((items, index) => {
        return (
          <li className="ProductList-product" key={items.id}>
              <h3>{items.title}</h3>
              <p>{items.description}</p>
              <div className="price-box">    
              <p>from: {items.price} $</p>
              </div>
              {items.photo
              ? <div>
                  {<img src={items.photo} alt=""/>}
                  {/* {console.log(items.photo.id)} */}
              </div>
              : <div></div>
          </li>
            
        );
      })}
  </ul>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.