4

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?

You Nguyen
  • 9,402
  • 4
  • 22
  • 49
Darius Cosden
  • 576
  • 10
  • 26

4 Answers4

2

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

izb
  • 551
  • 4
  • 10
2

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} />
}
neonfuz
  • 314
  • 1
  • 4
2

You didn't return anything in the map function argument. You can do that easily with a ternary expression and using es6 arrow notation:

 posts.map(post => (post.id < 2) ? <Post key={post.id} title={post.title} /> : null)
Hemadri Dasari
  • 29,321
  • 31
  • 106
  • 146
1

The second didn't work because you forgot the return statement.

Try this:

  <>
    {posts.map(post => {
      // changes are here
      if (post.id < 2) {
        return <Post key={post.id} title={post.title} />; //added return statement
      }
    })}
  </>
You Nguyen
  • 9,402
  • 4
  • 22
  • 49