1

Is there any chance to make this code DRY?

let allPosts = this.state.posts.map((item, i, arr) => {
  if (i === arr.length - 1) {
    return <Post
      key={item._id}
      post={item}
      nickname={this.props.nickname}
      ref={this.lastPostRef}
    /> 
  }

  return <Post
    key={item._id}
    post={item}
    nickname={this.props.nickname}
  />
});

The perfect solution would be

...
nickname={this.props.nickname}
if (i === arr.length - 1) {
  ref={this.lastPostRef}
} ...

but it doesn't work in React.

2

2 Answers 2

3

There is a cleaner way to do this without any conditions:

let allPosts = this.state.posts.map((item, i, arr) => {
  return <Post
      key={item._id}
      post={item}
      nickname={this.props.nickname}
      ref={el => this.lastPostRef = el}
    /> 
});

On every iteration of the loop, the last post ref will be updated with the latest element. By the end of the map, the last post will be set the to last post ref. Magic!

Sign up to request clarification or add additional context in comments.

1 Comment

It's a real magic because I don't understand now why I am able to get the post with this.lastPostRef and this.lastPostRef.current doesn't work for me. But I really like this variant.
2

Why not just let the property be undefined?

 return <Post 
    key={item._id}
    post={item}
    nickname={this.props.nickname}
    ref={ i === arr.length - 1 ? this.lastPostRef : undefined }
 />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.