0

I've got an array of strings which I'm rendering in my React app by mapping through them, like so:

{ state.map((item, index) => {
    return ( 
      <p className="width-90" contentEditable={true} onBlur={(e) => updateItem(e)}>{item}</p>
           )
})}

I'd like this paragraph to edit the overall 'state' array, by updating the string 'item' when the paragraph is blurred.

I'm attempting to do that, like this inside of the updateItem:

const updateItem = (e) => {

        // Take a copy of the array
        const arrayCopy = state

        // Search for the item in the item, using the innerHTML
        const foundItem = arrayCopy.find(() => e.target.innerHTML)

        // Find the element position of the item that I want to edit
        const elementPosition = arrayCopy.indexOf(foundItem)

        // Update the value of the target inside of the array copy
        arrayCopy[elementPosition] = e.target.innerHTML

        // Update the original array to be the new array
        setState(arrayCopy)
    }

It's attempting to find the item being edited in the overall state array, then use the index to update it.

However, it erratically seems to update state - sometimes it puts it to the start of the array, sometimes just removes certain elements.

Does anyone know what I'm wrong here?

Jon Nicholson
  • 927
  • 1
  • 8
  • 29
  • 2
    pass item and index to the event function. `onBlur={(e) => updateItem(e, index, item)}`. Then you don't have to look for the item. – Sergio Tx Apr 15 '23 at 10:37
  • `const arrayCopy = state` does not make a copy of the array, it simply creates a new reference to it. As such React doesn't see a change when you call `setState` because you've passed back the same reference. For a shallow copy you can use `const arrayCopy = [...state]`. see: [Fastest way to duplicate an array in JavaScript](https://stackoverflow.com/questions/3978492/fastest-way-to-duplicate-an-array-in-javascript-slice-vs-for-loop) – pilchard Apr 15 '23 at 10:48
  • Does this answer your question? [Why is useState not triggering re-render?](https://stackoverflow.com/questions/56266575/why-is-usestate-not-triggering-re-render) – pilchard Apr 15 '23 at 10:51
  • Passing in the index solved it for me. Thanks Sergio. – Jon Nicholson Apr 16 '23 at 11:10

1 Answers1

0

It looks like the issue with the code is that

"arrayCopy.find(() => e.target.innerHTML) "

does not actually search for the item in the array based on the innerHTML of the target element try this :

"const foundItem = arrayCopy.find((item) => item === e.target.innerHTML);"