Conditional Rendering in React js

前端 未结 3 2019
清歌不尽
清歌不尽 2020-12-07 04:55

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 &am         


        
相关标签:
3条回答
  • 2020-12-07 05:35

    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 讨论(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} /> 
    })}
    
    0 讨论(0)
  • 2020-12-07 05:45
    {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.

    0 讨论(0)
提交回复
热议问题