Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react - conditional rendering inside component return function

Tags:

reactjs

I would like to understand why react behaves this way.

This works

class Feed extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    const posts = [{ id: 1, title: 'post-1' }, { id: 2, title: 'post-2' }];
    return (
      <>
        {posts.map(post => (
          <Post key={post.id} title={post.title} />
        ))}
      </>

But this doesn't

class Feed extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    const posts = [{ id: 1, title: 'post-1' }, { id: 2, title: 'post-2' }];
    return (
      <>
        {posts.map(post => {
          // changes are here
          if (post.id < 2) {
            <Post key={post.id} title={post.title} />;
          }
        })}
      </>

It just returns blank. No errors.

What is the reason react isn't rendering this? And what would be the best approach to only render post-1?

like image 863
Darius Cosden Avatar asked Mar 06 '23 02:03

Darius Cosden


2 Answers

The arrow function syntax can accept either a value to return, or a block of code to execute. In the first example, you give a value: <Post key={post.id} title={post.title} />. However, in the second example you give a code block (by using {}). So, you need to either add return before <Post key={post.id} title={post.title}>like so:

{posts.map(post => {
  if (post.id < 2) {
    return <Post key={post.id} title={post.title} />;
  }
})}

or change the if into an && to keep the implicit return behavior:

{posts.map(post =>
  (post.id < 2) && <Post key={post.id} title={post.title} />
}
like image 184
neonfuz Avatar answered May 05 '23 21:05

neonfuz


You have to change it to return <Post ... />;

like image 37
izb Avatar answered May 05 '23 23:05

izb