Dynamically switch between showing more and showing less content on each div

Whenever the specific show more button is clicked, the content should be displayed without causing the entire component to re-render. I have tried using a useState, but each time the button is clicked, the whole component re-renders, resulting in long loading times for every div. Is there a simple solution to avoid this issue?

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>

prior to clicking showmore

https://i.sstatic.net/PyV11.png

upon clicking the showmore button on the second div https://i.sstatic.net/HLKaF.png

Answer №1

If you want to solve this issue, consider turning each box into a component. Create that component with the class "base component" because you will need to use getSnapshotBeforeUpdate.

getSnapshotBeforeUpdate: With this method, you can manage how your component renders. Remember, this method takes nextProps, nextState, and snapshot as parameters.

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


Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Managing line breaks in CSS

Here is a sample of HTML code with text lines breaking: <pre> one two three four five six </pre> I am looking to display it in the browser like this (with two lines per row and space using tab character "\t"): one two three four ...

The page is being enhanced with FontAwesome Styles through React rendering

I have managed to successfully incorporate various FontAwesome icons into my React App. However, I am facing an issue where the raw CSS styles from FontAwesome are also being rendered at the top of my page. Upon inspecting my page, I noticed a style elemen ...

React is a powerful tool that allows for the dynamic changing of state within

Struggling with my first React app and trying to accomplish something basic. The Input component in my app has an array in state, which sends two numbers and a unique ID as an object to a parent Component when the array has two numbers entered. Sending t ...

Can you indicate a specific version of an npm module without making changes to the package.json file?

I am looking to update the version of a npm module without making changes to the package.json file. I want to avoid forking the repository if possible. If the package.json appears similar to this: ... "dependencies": { "iwan ...

React hooks problem with toggle arrow functionality

Could anyone assist me with the following issue: I have a React Hooks component where I am trying to toggle an arrow when clicking on a span element. It currently works only once, and if clicked again, it does not work anymore. I am confused as to why th ...

Clearing AsyncStorage in React Native

It has come to my attention that I am spending a significant amount of time debugging redux actions in react-native that are being persisted to AsyncStorage using redux-persist. There are instances where I wish I could simply clear AsyncStorage in order to ...

Modification of encapsulated class in Angular is not permitted

Within Angular, a div element with the class "container" is automatically created and inserted into my component's HTML. Is there a way to modify this class to "container-fluid"? I understand that Angular utilizes encapsulation, but I am unsure of how ...

Best practices for server-side data fetching in Next.js 13 with App Router

Having a Next 13 app with the app router, I have a query about the optimal approach for fetching data: When it comes to retrieving data (such as fetching a list of posts), there are two options - either through the API client-side or directly in my react c ...

What is the best way to align an element at the center in Material UI library

I am working on an AppBar component for my Header, and my goal is to center the title within the AppBar. I want a button aligned to the left and another one aligned to the right. These buttons should be positioned flush against their respective sides. con ...

Seeking a template for a server-side programmer who lacks proficiency in CSS and design?

Hey there all you wise folks! So here's the deal - I'm a PHP/JavaScript wizard when it comes to logic and server-side stuff, but I really suck at design, CSS, and all things arty. Does anyone have any recommendations for a template or tool that ...

Alert: Github Dependabot has flagged Babel as vulnerable to arbitrary code execution when compiling meticulously designed malicious code

My Github Repository's Security section is flagging this issue as Critical for both my Frontend and Backend code. I'm having trouble grasping the nature of this alert. Can someone explain what flaw it represents? After updating my dependencies, ...

Error: You forgot to close the parenthesis after the argument list / there are duplicate items

I have already tried to review a similar question asked before by checking out this post, but unfortunately, I still couldn't find a solution for my problem. Even after attempting to add a backslash (\) before the quotation mark ("), specificall ...

The AWS lambda function is experiencing difficulties with the AWS.HttpClient handleRequest operation

In my Node.Js lambda function, I am utilizing AWS HttpClient's handleRequest to search an ElasticSearch URL using the AWS SDK. I am following the guidelines provided in the AWS Documentation. Click here for more information on ES request signing. Pl ...

Error encountered when attempting to create an index in ElasticSearch due to

I am encountering an issue with the elasticsearch npm module while attempting to create an Index, resulting in a TypeError with the following message: Unable to build a path with those params. Supply at least index The code snippet I am using is as follo ...

Notifying with Socket.IO in Node.js

Hey there, I'm currently working on implementing a notification system but have hit a roadblock. I've sent an invitation to a user to join the club. socket.on("notify", async (message) => { // invite the user John Doe io.to('socke ...

Typescript Next.js Project with Custom Link Button Type Definition

I have a project that includes a custom Button component and a NextLink wrapper. I want to merge these two components for organization purposes, but when I combine the props for each, I encounter an issue with spreading the rest in the prop destructuring s ...

What is the best way to establish a minimum width in pixels and a maximum width determined by the variable width of the browser window?

In this scenario: http://jsbin.com/anoyik/edit#preview http://jsbin.com/anoyik/edit#source Is there a way to make the red box's width a minimum of 200px and allow it to expand as the browser window's width increases horizontally? ...

Authenticating Users with Laravel and Vue.js

In my Vue.js application, I have implemented a login system. The main script in my main.js file includes the necessary imports and configurations: import Vue from 'vue'; import NProgress from 'nprogress'; import Resource from 'vue ...

What could be causing the block to fail in the event of an AJAX request?

I have encountered an issue with my PHP file and AJAX setup. The if block in my code is working properly, but the else block seems to be not functioning as expected. Even after changing the condition from data!= null to data== null, the problem persists wh ...

Guide to incorporating trading-vue-js into a Vue CLI project

Recently, I decided to explore the functionality of trading-vue-js and found it quite interesting. I managed to successfully run the test examples for trading-vue-js without any issues. The steps I took were as follows: nmp install trading-vue-js I then ...