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 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>
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.
1.4m articles
1.4m replys
5 comments
56.9k users