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.

1

3 Answers 3

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.

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

Comments

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

Comments

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

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.