What is the best way to remove a div card along with its content in a React application?

https://i.sstatic.net/IlXwE.gif

Encountering an issue similar to the gif image provided. Upon deleting the first card, the content of the subsequent card is also removed. How can this be prevented?

state = {
        data: '',
        todoCard: [],
        id: 0,

    }
    addCard() {

        this.setState({ id: this.state.id + 1, todoCard: [...this.state.todoCard, this.state.id] })
    }
    deleteCard(id) {
        this.setState({
            todoCard: this.state.todoCard.filter(item => item !== id)
        });
    }

The addition and deletion of the div card are managed through these functions.

 <div className="pageContainer">
                    <CreateCard onClick={this.addCard.bind(this)} />
                    {this.state.todoCard.map((e, i) => (
                        <TodoCard deleteCard={() => this.deleteCard(e)}
                            key={i}
                            value={e} />
                    ))}
                </div>

Creation of the added cards follows this format.

class TodoCard extends Component {
    state = {
        newItem: "",
        list: []
    }
    handleChange(event) {
        this.setState({ newItem: event.target.value })
    }
    addItem(event) {
        event.preventDefault();
        const newItem = {
            id: 1 + Math.random(),
            value: this.state.newItem.slice(),
            checked: false
        };
        //Validation with if-else statement for input
        if (newItem.value === "") {
            alert("Cannot enter blank information")
        }
        else {
            const list = [...this.state.list];
            list.push(newItem);
            this.setState({
                list,
                newItem: ""
            })
        }

    }

    deleteItem(id) {

        const list = [...this.state.list];
        const updatedList = list.filter(item => item.id !== id);
        this.setState({ list: updatedList });


    }
    checkItem(id) {
        this.setState({
            list: this.state.list.map(item => {
                if (item.id === id) {
                    return {
                        ...item,
                        checked: !item.checked
                    }
                }
                else {
                    return item;
                }
            })
        })

    }
    render() {
        return (
            <div className="card">
                <TodoForm onChange={this.handleChange.bind(this)} value={this.state.newItem} submit={this.addItem.bind(this)} />
                <hr />
                <button onClick={this.props.deleteCard}>Delete</button>
                <p>{this.props.value}</p>
                <ul>
                    {this.state.list.map(item => {
                        return (
                            <li className="list" key={item.id}>
                                <input onClick={() => this.checkItem(item.id)} className="checkbox" type="checkbox" />
                                <label style={{ textDecoration: item.checked ? "line-through" : "" }}>{item.value}</label>
                                <button className="deleteButton" onClick={() => this.deleteItem(item.id)}>X</button>
                            </li>
                        )
                    })}

                </ul>
            </div>

        )
    }
}

The content of the card behaves as expected when deleting the last card, but issues arise when deleting the first card, resulting in the removal of the next card's content.

Answer №1

It is important to always refer to the previous state when updating it in React.

this.setState(prevState => {
      return {
        num: prevState.num + 1
      }
    });

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

Failure of app script to retrieve data from an external spreadsheet

In an attempt to consolidate data, this program aims to transfer information from one spreadsheet to another. The process involves retrieving all files within a designated folder (all of which are spreadsheets), extracting values from a specific range, and ...

Angular JS allows for the display of text from a textarea upon clicking the submit button

Q] How can I display a single text message from a textarea upon clicking the submit button in angular-js? Here is the current code that I have: <html ng-app="myApp"> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1 ...

What is the method for adding a clickable primary choice in Material UI Labs Autocomplete?

Here is an example from the MUI docs on Autocomplete demonstrating a link to Google that is not clickable. The event target only captures the MuiAutocomplete component instead of the <a> element being passed. import React from "react"; import TextFi ...

The React Bootstrap Table features a button in every row that triggers a modal. However, clicking on a specific button causes the modal to render multiple times

I have a React Bootstrap Table, with 20 records displayed on each page. Each row contains a button added through the following code: function attachFormatter(cell, row){ return ( <AttachmentManager /> ); } <TableHeaderColumn k ...

Transferring a JavaScript variable to a PHP file through jQuery's Ajax functionality

I'm having trouble figuring out how to pass a JavaScript variable to a PHP script using AJAX. This is my first attempt at using AJAX and I seem to be missing something. Here's the code snippet: function selectCategory(value) { $.ajax({ ...

Encountered a problem while trying to upload a video on bunny stream using node.js

Having trouble uploading videos to the Bunny Stream API using Node.js and Axios. Everything else seems to be working fine, like fetching, deleting, changing names, and resolutions of videos. However, when trying to upload a video, consistently receiving 40 ...

Endlessly triggering document.execCommand, the JavaScript selectionchange-EventListener seems to have a mind of

I recently implemented an event listener for selectionchange in the following manner: document.addEventListener("selectionchange", function() { highlight(); console.log("selectionchange-triggered"); }, false); After that, I included the code bel ...

Verify whether an item exists within a nested array in ReactJS

Here is the dataset that I have: Data: data: { id:1 groups:[ {id:1 , name: john, permissions : [{id:1 , codename="can_edit"},{id:2,codename="can_write"},{id:3,codename="can_delete"}]} , ...

Discover the way to utilize the java enum toString() function in jQuery

In my Java Enum class called NciTaskType, I have defined two tasks: Pnd Review Woli and Osp Planning. public enum NciTaskType { PndReviewWoli, // 0 OspPlanning, // 1 ; @Override public String toString() { switch (this) ...

Deactivate the linear x axis labels in jQChart

I have a jQchart Linear chart that is displaying correctly and functioning properly. I am looking to remove or disable the X axis labels from the chart. ...

The navigation bar has surpassed the content limit and overflow-y is visible

My website has a navigation bar with content that exceeds the desired limit, and I want the rest of the content to be shown in overflow-y. However, an issue arises when hovering over the content, as the content is displayed (likely due to fixing min-heigh ...

GraphQL Error (Status Code: 429) - Next.js Development issue

If you're facing a GraphQL Error (Code: 429) while working on a nextjs project, here's a handy solution. Here's what happened: I created a headless CMS using Hygraph and NextJS 13 for a blog project. I also utilized the npm package graphql ...

Building a matrix of checkboxes

I am looking to design a grid of checkboxes that are displayed in columns, with 5 checkboxes in each column. <ul class="checkbox-grid"> <li><input type="checkbox" name="text1" value="value1" /><label for="text1">Text 1</lab ...

Transferring data in React Router using React

Hey everyone, I'm currently facing an issue with transferring data between two components that are not related. The code snippet below is what I have so far, but I'm stuck on how to access it from the other component: <Button className=&apo ...

Ensure that the input value in the MUI autocomplete feature remains persistent after a selection has

When using Material-UI Autocomplete with Multiple, the entered value gets cleared after selecting an option. https://i.sstatic.net/TE9Iu.png Is there a method to maintain the inputted value even after making a selection? Similar to the example below... ...

Error code EPERM encountered while attempting to append a file on a network

An issue arises when the application is required to store log data on a network drive. While everything works smoothly when the drive is hosted under Windows, complications arise when it is hosted on a Mac. Read/write operations function properly, but appe ...

Ajax sends the URL location to Python

I'm attempting to piece together some code. There are two distinct functions that I am trying to merge into a single entity. Code snippet: <!DOCTYPE html> <head> <meta http-equiv="content-type" content="text/html;charset=UTF-8"> &l ...

Modifying React state within nested setTimeout callbacks

Could someone please help me understand why the 'video variable' state remains false even after the h2 element has rendered and is visible? When I click to call the hideVideo function, the video state doesn't change. Thank you for your assis ...

TaffyDB is throwing an error message indicating that TAFFY is not recognized as a function

I am currently developing a web-based game using HTML, CSS & JavaScript within Visual Studio and utilizing TaffyDB as my database. However, I have encountered an error when trying to create a database using the TAFFY function, as it keeps showing up in the ...

Searching for information about a logged-in user's data through Graphql and AWS Cognito

I have been working on querying a user's specific data using AWS Cognito, Appsync, and Graphql. After updating my Schema rules to include @auth, I encountered an unauthorized error when trying to fetch the data. Previously, without @auth, I was able t ...