Prajila V P
Prajila V P

Reputation: 5337

Conditional Rendering in React js

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.

Upvotes: 1

Views: 1762

Answers (3)

Broda Noel
Broda Noel

Reputation: 2026

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} /> 
  );
}

Upvotes: 2

B.Shrestha
B.Shrestha

Reputation: 136

{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.

Upvotes: 7

Mayank Shukla
Mayank Shukla

Reputation: 104499

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} /> 
})}

Upvotes: 2

Related Questions