Search code examples
javascriptnode.jsreactjslistreact-redux

react js not rendering properly after removing item from list


i am trying to remove item on click from a list in react js. but i click on delete button it remove the last item from list not the one i clicked. if i check in console.log it show the correct output but not rendering it correctly. i have tried to remove item in many different ways . here is my codesandbox link for poroject https://9o0jw.csb.app/ i don't know what i am doing wrong here is my code snippet

{projects &&
            projects.map((project, key) => (
              <div
                key={`editProject-${key}`}
                className="d-sm-flex justify-content-between align-items-center mb-2"
              >
                <div className="flex-sm-fill">
                  <div className="project-input-field">
                    <input type="text" defaultValue={project.title} />
                  </div>
                  <div className="project-input-field">
                    <input type="url" defaultValue={project.link} />
                  </div>
                </div>
                <div className="remove-project">
                  <button onClick={() => removeProject(project.title)}>
                    Remove Projoect
                  </button>
                </div>
              </div>
            ))}

And here is delete function

 const removeProject = title => {
    // let newProjects = projects;
    // newProjects = newProjects.filter(project => project.title !== title);
    // setProjects(newProjects);
    setProjects(prevProject => {
      return prevProject.filter(pro => pro.title !== title);
    });
  };

Solution

  • I'd look at key={`editProject-${key}`} - you're using the array index so react thinks that the removed key is the last index when it re-renders. If the project.title is unique, then use that as the key.

    However if project.title is not unique, then look to create a unique id when a project is created.

    More info https://reactjs.org/docs/lists-and-keys.html