show more and show less dinamicaly for each div

Viewed 30

when I click the particular show more button the content should be displayed, the condition is the whole component should not re-rendering
I have used a useState when I clicked the button it is re-rendering the whole component it is taking a long time to re-render every div give an easy solution for this.

const [arr,setmarr] =useState([])
const oncl=(e)=>{
setarr((prev)=>[...prev,e.target.value])
}
return{
divarray.map((i,j)=>{
        {console.log("tdic)")}
        return(
          <Commentbox divarr={arr[j]} value={j} oncl={(e)=>oncl(e) } />
        )
        }
      }

Commentbox component

return 
<div>
  div{j}

// some icons here

{divarr && <div> right side div </div>}
<button onClick={(e)=>{oncl(e)}}  value={j} >see more</button >
</div>

before onClick on showmore

enter image description here

after showmore button has been clicked on the second div enter image description here

1 Answers

you should change each box to a component to solve this problem. make that component with class base component because you need getSanpShotBeforeUpadte.

getSanpShotBeforeUpadte: you can control your component's render with this method.dont forget this method will give you nextProps,nextState and snapshot as parameter

class Box extends Component{
  state = {
    // more
    showMore: false,
  }

  getSnapshotBeforeUpdate(nextProps,nextState){
    // OTHER CONDITIONS
    
    if(nextState.showMore !== this.state.showMore) return true
    return false
  }

  render(){
    return (
      <div>
        {/* CODE ... */}
        <div style={{display: this.state.showMore ? 'block' : 'none'}}>
          HERE IS A TEXT 
        </div>
        <button onClick={()=>this.setState({showMore: !this.state.showMore})}>show more</button>
      </div>
    )
  }
}


Related