Dreams
Dreams

Reputation: 8506

How to make html code as a variable and use it?

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?

Upvotes: 0

Views: 46

Answers (2)

Mario Santini
Mario Santini

Reputation: 3003

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.

Upvotes: 1

Learning
Learning

Reputation: 305

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

Upvotes: 1

Related Questions