Ad

React Map - Don't Return Item If Missing

- 1 answer

I'm using map in react to show a feed of facebook posts, but i don't want the post to render if the message field is missing from the json data.

If I do this I get an error ('if' is an unexpected token) and my project won't build

return (
        <Slider
          {...Settings}>
          {postsAvailable && posts.map((post, index) => (
            if (!post.message) return null
            return (<div key={post.id}>
              { index === 0 && <Item /> }
              { index > 0 && <div className='item'>
                <img data-original={post.full_picture} className='img-responsive' />
                <div className={`facebook-content slide-${post.id}`}>
                  <p className='text'>{post.message}</p>
                </div>
              </div> }
            </div>)
          ))}
        </Slider>
      )
Ad

Answer

You are not giving your function given to map a body. Change () to {} and it will work as expected.

return (
  <Slider {...Settings}>
    {postsAvailable &&
      posts.map((post, index) => {
        if (!post.message) return null;
        return (
          <div key={post.id}>
            {index === 0 && <Item />}
            {index > 0 && (
              <div className="item">
                <img
                  data-original={post.full_picture}
                  className="img-responsive"
                />
                <div className={`facebook-content slide-${post.id}`}>
                  <p className="text">{post.message}</p>
                </div>
              </div>
            )}
          </div>
        );
      })}
  </Slider>
);

Alternatively you could filter out all the posts that don't have a message first and then map those that does.

return (
  <Slider {...Settings}>
    {postsAvailable &&
      posts
        .filter(post => post.message)
        .map((post, index) => (
          <div key={post.id}>
            {index === 0 && <Item />}
            {index > 0 && (
              <div className="item">
                <img
                  data-original={post.full_picture}
                  className="img-responsive"
                />
                <div className={`facebook-content slide-${post.id}`}>
                  <p className="text">{post.message}</p>
                </div>
              </div>
            )}
          </div>
        ))}
  </Slider>
);
Ad
source: stackoverflow.com
Ad