Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to not render element if it's null?

I want to render news feed. Articles can have titles, pictures, and author names. I render it like this:

render() {
    const newsItem = (article, id) => (
      <article className="news-item" key={id}>
        <img className="news-picture" src={`${article.urlToImage}`} alt=""/>
        <h1 className="news-title">{article.title}</h1>
        <p>Author: {article.author}</p>
      </article>
    );

    const newsFeed = this.state.news.map(e => newsItem(e, pushid()));

    return (
      <div className="news-feed">{newsFeed}</div>
    );
  }
}

Some times API doesn't give author names (the value is null), and if so, I don't want to render

<p>Author: {article.author}</p>

How is it done correctly in react?

like image 660
Max Popov Avatar asked Mar 19 '26 06:03

Max Popov


1 Answers

Try this:

{article.author && <p>Author: {article.author}</p>}

This means that if article.author exists or is not null then render <p>...</p>.

This is the same as it would have been with an if statement, except that you can't write if statements here. This is the equal of that.

if(article.author) return <p>Author: {article.author}</p>
like image 128
Ertan Hasani Avatar answered Mar 20 '26 20:03

Ertan Hasani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!