M
M
Marat Ivanov2019-06-11 15:33:09
JavaScript
Marat Ivanov, 2019-06-11 15:33:09

Using && on render in react?

Hey!
As for the very beginners, please explain what role does it play here &&?
{ news && news.map(newsItem =>....

Container:

class News extends React.Component {
  state = {};
  componentDidMount() {
    const url =
      "https://newsapi.org...";
    fetch(url)
      .then(responce => responce.json())
      .then(m => this.setState({ news: [...m.articles] }));
  }
  render() {
    const { news } = this.state;
    return (
      <Wrapper>
        <div style={{ width: "100%" }}>
          <Typography variant="h2" component="h1" gutterBottom>
            Новости
          </Typography>
        </div>

        { news &&
          news.map(newsItem => (
            <Card
              title={newsItem.title}
              key={
                new Date(newsItem.publishedAt).getTime() - Math.random() * 25
              }
              urlToImage={newsItem.urlToImage}
              description={newsItem.description}
            />
          ))}
      </Wrapper>
    );
  }
}
export default News;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2019-06-11
@mrair

In this case, the block will only exit if news is not undefined, null, or 0.

news.map(newsItem => (
            <Card
              title={newsItem.title}
              key={
                new Date(newsItem.publishedAt).getTime() - Math.random() * 25
              }
              urlToImage={newsItem.urlToImage}
              description={newsItem.description}
            />
          ))

google react conditional rendering

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question