1

I'm handling data I read from Newsapi.org. The problem is that sometimes I get the news title but the image url returns null.

I did this to do conditional rendering so it shows another image when the return variable is null. It is not showing the replace image when the response is null.

<div class="col-2">
          { article.urlToImage != 'null' ? 

            <a href={article.url} class="thumbnail">
              <img src={article.urlToImage} class="img-fluid" />
            </a>
          : 
            <a href={article.url} class="thumbnail">
              <img src="http://www.publicengagement.ac.uk/sites/default/files/styles/content_width/public/hero/large-crowd-of-people-small.jpg" class="img-fluid" />
            </a>
          }  
</div>
tarek hassan
  • 772
  • 11
  • 35

2 Answers2

1

'null' is string and you're checking with string. Change 'null' to null object.

{ article.urlToImage != null ? 

But, I would simply do like:

<a href={article.url} class="thumbnail">
  <img src={article.urlToImage || 'default-path-of-the-image' } class="img-fluid" />
</a>

This satisfies if the article.urlToImage is null or undefined use the default image default-path-of-the-image otherwise use the image from article.urlToImage.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
0

A better code will be :

<div class="col-2">
        <a href={article.url} class="thumbnail">
          <img src={article.urlToImage != 'null'? article.urlToImage : 'http://www.publicengagement.ac.uk/sites/default/files/styles/content_width/public/hero/large-crowd-of-people-small.jpg' } class="img-fluid" />
        </a>     
</div>
Anil Kumar
  • 2,223
  • 2
  • 17
  • 22