最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Conditional Rendering in React js - Stack Overflow

programmeradmin5浏览0评论

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.

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.

Share Improve this question asked Jun 20, 2017 at 9:51 Prajila V PPrajila V P 5,3373 gold badges27 silver badges37 bronze badges 1
  • Does this answer your question? if-else statement inside jsx: ReactJS – Emile Bergeron Commented Nov 4, 2019 at 20:32
Add a ment  | 

3 Answers 3

Reset to default 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.

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

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} /> 
  );
}
发布评论

评论列表(0)

  1. 暂无评论