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?