5

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,961
  • 4
  • 26
  • 52
Darius Mandres
  • 778
  • 1
  • 13
  • 31

4 Answers4

2

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

izb
  • 562
  • 4
  • 11
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
  • 32,666
  • 37
  • 119
  • 162
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,961
  • 4
  • 26
  • 52