'Mapping React Components into 'contentEditable' element. How to work around Node.removeChild error when a component is deleted via backspace?

I'm working on a discord clone and trying to implement a 'mentions' feature into the chat bar.

My element looks like this:

       <span
          contentEditable
          suppressContentEditableWarning={true}
          onInput={(e) => {
            setMsg(e.target.innerHTML);
          }}
        >
          {mentions &&
            mentions.map((obj, i) => {
              return (
                <>
                  <MentionWrapper
                    key={i}
                    displayName={obj.displayName}
                    uid={obj.uid}
                    id={obj.id}
                  />
                  <span>&nbsp;</span>
                </>
              );
            })}
        </span>

I'm running into problems when I delete one of the 'mention' components via backspace. If I try to set state on the mentions variable anytime afterwards, React re-renders and I get an error.

Node.removeChild: The node to be removed is not a child of this node contentEditable

I get why this is happening. I was just wondering if there was a way to work around this.



Solution 1:[1]

Atm I'm using key to solve the error when the array changes length

 <span
          key={mentions.length}
          contentEditable
          suppressContentEditableWarning={true}
          onInput={(e) => {
            setMsg(e.target.innerHTML);
          }}
        >
          {mentions &&
            mentions.map((obj, i) => {
              return (
                <>
                  <MentionWrapper
                    key={i}
                    displayName={obj.displayName}
                    uid={obj.uid}
                    id={obj.id}
                  />
                  <span>&nbsp;</span>
                </>
              );
            })}
        </span>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jlee