aBloomer aBloomer - 3 months ago 12
React JSX Question

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´╝č

Answer

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.