1

I have added a condition in rendering and suddenly it stops displaying. Here is the code am using.

 {this.state.sdata.map((sdata, i) => 
   {i < 5 && 
    <ServiceNavItem key={i} onClick={()=>this.handleSelect(i)}{...sdata} /> 
   }
  )
 }

I want to display only 4 items from sdata. Anybody please help.

Prajila V P
  • 5,027
  • 2
  • 23
  • 36
  • Does this answer your question? [if-else statement inside jsx: ReactJS](https://stackoverflow.com/questions/44046037/if-else-statement-inside-jsx-reactjs) – Emile Bergeron Nov 04 '19 at 20:32

3 Answers3

7
{this.state.sdata.map((sdata, i) => 
     (i < 4 && 
       <ServiceNavItem key={i} onClick={()=>this.handleSelect(i)}{...sdata} /> 
     )
   )
}

Just replace the {} with () like shown above and to show 4 data you have to provide less than 4 because i starts with 0.

Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
B.Shrestha
  • 136
  • 5
2

You forgot to return the element from map body, as well as you need to return null for all the entries of array after i >= 5.

Write it like this:

{this.state.sdata.map((sdata, i) => {
       if(i < 5) 
          return <ServiceNavItem key={i} onClick={()=>this.handleSelect(i)}{...sdata} /> 
       return null;
   })
}

But i will suggest you to use for loop instead of map to create only 5 elements.

If you want to use map then first use slice and create a sub array of 5 elements then use map on that.

Like this:

{this.state.sdata.slice(0,5).map((sdata, i) => {
     return <ServiceNavItem key={i} onClick={()=>this.handleSelect(i)}{...sdata} /> 
})}
Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
2

You can also try alternatives of conditional rendering from here: Conditional Rendering in React and the JSX solution

Basically, the proposal is to create a "Conditional" Component, and use it like:

<Conditional if={this.state.something}>
  <div>hello!</div>
<Conditional>

So, <div>hello!</div> is going to be rendered only if this.state.something is true.

In your example, it should be implemented in this way:

{
  this.state.sdata.map((sdata, i) => 
    <Conditional if={i < 5}>
      <ServiceNavItem key={i} onClick={()=>this.handleSelect(i)}{...sdata} /> 
    </Conditional>
}

Anyways, the best way to show only 5 elements is to do: Basically, get only the first 5 elements from the array and do a .map in that Array.

{
  this.state.sdata.slice(0, 5).map((sdata, i) => 
    <ServiceNavItem key={i} onClick={()=>this.handleSelect(i)}{...sdata} /> 
  );
}
reisdev
  • 3,215
  • 2
  • 17
  • 38
Broda Noel
  • 1,760
  • 1
  • 19
  • 38