最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to not render element if it's null? - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Apr 16, 2019 at 13:07 Maksym PopovMaksym Popov 4521 gold badge8 silver badges18 bronze badges 1
  • What you mean by null. Empty string or actual null? – Maheer Ali Commented Apr 16, 2019 at 13:12
Add a ment  | 

3 Answers 3

Reset to default 4

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>

Just check existence with short circuiting &&

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

How it works ?

x && y
|
|___________ if x true move ahead and execute `y` else don't
render() {
const newsItem = (article, id) => {
  if (!article.author) {
    return null;
  }
  <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>
);

} }

Just put the if condition as mentioned above. So that if it is null you can return null.

发布评论

评论列表(0)

  1. 暂无评论