Jasper Huang
Jasper Huang

Reputation: 569

React.js: Getting "Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node."

I have a <span> element that is inside of a contentEditable <div>. In certain situations, when I try to delete everything in the <div> at once with Command-Delete, or when I try to delete individual characters from the <span> element when it is the only thing inside of the <div>, I get the error in the title.

How can I go about fixing this?

I put together a sandbox example of the issue: https://codesandbox.io/s/nostalgic-wildflower-52eul?file=/src/App.js

It throws the error under two circumstances (the keyword in the example is test, it should get highlighted in blue when you type it):

  1. Type any string with test inside of it or just test and highlight everything and delete.
  2. Type any string with test inside of it, delete everything else except for test, then delete any character in test.

Thanks for any help!

Upvotes: 1

Views: 13952

Answers (2)

Abhishek Agarwal
Abhishek Agarwal

Reputation: 31

Just give the key to the parent element i.e div className='app ' according to your code or add a new parent element and just give the key to that element.

and if anything changes and you get this error, just update the key of the parent element 

Because updating that parent element key causes react to detach the parent element from its dom, you can avoid this error because the problem is with the child element.

In onInput just check if the elemeent with id="addItemInput" is present or not and if it is not there just update the parent element key

Upvotes: 2

Rodrigo Ehlers
Rodrigo Ehlers

Reputation: 1840

You most probably read the following error when you set contentEditable of your div to true:

Warning: A component is `contentEditable` and contains `children` managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated. This is probably not intentional.

The problem here is that you let React add a child node to the content editable div and remove it through the actual DOM when interacting with it and removing all of its content.

React tries to re-render, and remove the span that should not be existent on next render however, you already removed it through your keyboard input.

You should only suppress the warning if you're absolutely sure about what you're doing, as it is warning you about the exact error you're getting.

The solution you're going for will not work as you would like it to.

You could be better off trying to implement an edit mode and highlighting the words after the user saves the content. This is only an idea as I don't know exactly what you're trying to achieve.

More info on this: https://stackoverflow.com/a/49639256/7381466

Upvotes: 3

Related Questions