Is there a way to remove a dynamically rendered component from a list?

Whenever I click a button, the same component is dynamically rendered on top of the list. But now, I need to implement a feature where users can delete any component from the list by clicking a cancel button associated with each component.

Here's my current progress:

Local state:

state = {
    formCount: 0
}

Add and Cancel functions:

onAddClicked = () => {
    this.setState({formCount: this.state.formCount + 1});
}

onCancelButtonClicked = (cancelledFormKey: number) => {
    const index = [...Array(this.state.formCount).keys()].indexOf(cancelledFormKey);

    if (index > -1) {
      const array = [...Array(this.state.formCount).keys()].splice(index, 1);
    }
}

Parent component snippet:

{ [...Array(this.state.formCount).keys()].reverse().map(( i) =>
                            <Form key={i} 
                                      onCancelButtonClicked={() => this.onCancelButtonClicked(i)}
                            />)
                        }

The challenge I'm facing is keeping track of which form was deleted. I believe I need to create a new object in my state to keep track, but since I'm using an array based on count, I'm not sure how to identify the exact index of the removed form. Any suggestions on how to achieve this?

Answer №1

Typically, creating a list of items in this manner is not recommended. By not storing the form data in the parent and using index-based keys, you run the risk of causing issues when modifying the array. For example, if you have an array with five elements [0, 1, 2, 3, 4], and you remove an item at index 2, the indices of all subsequent items will shift, leading to key changes and re-renders in React. Since the data isn't stored in the parent component, you may lose them.

However, if you insist on using indexed keys, one approach could be to keep track of removed indexes and filter them out. A solution like the following might work:

state = {
    formCount: 0,
    deletedIndex: []
}

onCancelButtonClick = (cancelledIndex: number) => setState((prevState) => ({
         deletedIndex: [...prevState.deletedIndex, cancelledIndex]
});

Your render function would then resemble:

{ 
    [...Array(this.state.formCount)].keys()].reverse().map((i) => (
        if (deletedIndex.includes(i) {
            return null;
        } else {
            <Form key={i} ... />   
        }
    ))
}

Generally speaking, it's best to avoid using index-based keys even for non-performance critical scenarios. This practice can lead to inconsistencies and conflicts between UI and state. If you choose to use index-based keys anyway, ensure that the components rendered with these keys have their data managed at the parent component level.

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

Redux store values resetting to initial state when changing views

I am encountering an issue where, upon switching routes, the value of a property in my store is reverting back to its original state. This occurs while using react 16 with react router v4. Additionally, I have observed that the entire App component re-ren ...

Angular Inner Class

As a newcomer to Angular, I have a question about creating nested classes in Angular similar to the .NET class structure. public class BaseResponse<T> { public T Data { get; set; } public int StatusCo ...

Tips on implementing npm's node-uuid package with TypeScript

Whenever I attempt to utilize node-uuid in TypeScript, I encounter the following issue: Cannot find module uuid This error occurs when I try to import the uuid npm package. Is there a way to successfully import the npm uuid package without encountering ...

The main content will be displayed on the sub-routes of the child

I'm feeling uncertain about the routes for children. For example, I have an 'About' route with 'me' as a sub-route: { path: '/about', name: 'About', component: About, children: [ { ...

Trouble arises when incorporating a new feature onto a map with OpenLayers and Vue.js

I'm currently working on integrating a custom control into my map using OpenLayers with Vue.js. The Explore.vue component is responsible for creating the "map" (olmap) with OL, and I bind it to the child component LeftSideBar2.vue. However, when att ...

The functionality of my script relies on the presence of an alert function within it

My code seems to only work when I include an alert function in it. I'm trying to make my div scroll to the bottom. I've done some research, but for some reason, the script doesn't run without an alert function. $(document).ready(function ...

How can I use JavaScript to trigger a button click event inside an iframe element

Is there a way to retrieve the inner HTML contents of a clicked element in an iframe loaded content using JavaScript? This code uses jQuery: var elements = document.getElementsByTagName('iframe'); [].forEach.call(elements, function(elem ...

Calculating the sum in a VueJS pivot table

Currently, I am delving into VueJS and working on migrating a basic application from Laravel with the blade template engine. The backend remains unchanged, consisting of a straightforward RESTful API with 3 tables: Books, Places, and a pivot table named B ...

When utilizing jQuery to add a <li> element, it suddenly vanishes

? http://jsfiddle.net/AGinther/Ysq4a/ I'm encountering an issue where, upon submitting input, a list item should be created with the content from the text field. Strangely, it briefly appears on my website but not on the fiddle, and no text is appen ...

Error encountered when passing props to child components in NextJS

I have a file that defines two types: type IServiceItems = { fields: { name: string; description: string; logo: { fields: { file: { url: string; }; }; }; }; }; type ITechItems = { fields: { n ...

flickering image when shared using react-navigation-fluid-transitions

Currently, I am in the process of mastering the art of creating stunning animations using react native. However, I am facing some difficulties while working with the react-native-fluid-transitions library. My issue arises when using shared elements with i ...

Flask - Refreshing Forms Dynamically

In an effort to enhance the responsiveness of my app, I am looking for a way to prevent the page from reloading every time a POST request is sent. My current setup includes a dynamically generated form with input fields designed like this: <div class=&q ...

Retrieve JSON Data Using Angular in a Wordpress Environment

I need assistance with displaying a JSON Array in <li>'s within a Wordpress Template. Here is the specific JSON file: I am completely unfamiliar with how to achieve this. This is the HTML code I have: <div ng-app="appExtern" ng- ...

Utilize select2 for dynamically loading an external html component

When the page is loaded, it includes another HTML page with a select element that I want to style using select2. The basic page structure looks like this: <select class="selectAddItem" id="selectAddItem" name="selectAddItem" style="width: 150px;" clas ...

Is it possible to eliminate the arrows from an input type while restricting the change to a specific component?

Is there a way to remove the arrows from my input field while still applying it only to the text fields within this component? <v-text-field class="inputPrice" type="number" v-model="$data._value" @change="send ...

I am experiencing an issue where emojis are not displaying properly on Facebook, Instagram, and LinkedIn when I share posts from my

I've developed a unique social media management application that enables users to automatically post on their social profiles using the Facebook, Instagram, and LinkedIn APIs. Everything is functioning well, except for one issue - my Emojis are not di ...

How can I update the value of a Material-UI v4 textField using Redux-form?

How can I update the value of a TextField using redux-form? My current version includes: "@material-ui/core": "^4.11.0" "redux-form": "^8.3.6" Prior to implementing redux-form, I was able to update the TextFiel ...

Using Javascript and jQuery to create an infinite animated background change with fade effect

I am struggling to figure out how to automatically change the background of a div every 3 seconds, looping through a series of images. I posted about this issue before but didn't receive much help. function animate() { change1(); change2() ...

"Interact with jQuery by sliding side to side or in a circular motion

I am in need of assistance with sliding images using jQuery back and forth, or making them go round in a loop. Currently, the images slide up to the last element and then swiftly return to the first div, which is not visually appealing at all. I understa ...

Manage and persist global data across all components in Next.js with fetching capabilities

For my Next.js application, I am looking to efficiently retrieve JSON data from an API that will be shared among all components. What is the best approach to ensure that multiple calls are not made for the same API within each component? ...