0

Below is my sample code .....

<ul>
  {this.state.showAllUser == false 
        ? someArray.slice(0, 3).map(function(user, index) {
              return (
                    <li key={index}> {user.name}<li>
              )
        : someArray.map(function(user, index) {
              return (
                    <li key={index}> {user.name}<li>
              )
  }
</ul>

If this.state.showAllUser is false, i will only show three of array or show all of them if true.

My question is how to make this code more clean , can I make a function or variable and use it in refer function?

0

2 Answers 2

1

You could use the Array method instead, like so:

<ul>
      {someArray.filter(function(el, index) {
        if (!this.state.showAllUser) {
          // Print the first 3 elements
          return (index < 3)
        } else {
          // Print all
          return true
        }
      })
      .map(function(user, index) {
        return (<li key={index}> {user.name}</li>)
      })
    }
</ul>

In this way it is very clear where you control which elements are going to be shown and which are not.

And more you write only once the virtual DOM part.

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

1 Comment

Thanks a lot.It really helps me.
1
<ul>
  {
    (this.state.showAllUser == false ? someArray.slice(0, 3) : someArray).map((user, index) => <li key={index}> {user.name}<li>);
  }
</ul>

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.