Working on the RecipeApp React challenge I encountered a problem with passing the index value of this.state.recipes.map((recipe,index) into function delHandler()
- the index variable seems not to be passed at all and is undefined, but why?
- if the third element is clicked it deletes the second element instead, is this a problem caused by #1
Problem solved as follows:
- using native react index in lists that change dynamically will cause problems, so I added an id property to each element of the object to use as key.
- this id is now passed to the
delHandler() on click as
(e) => this.delHandler(recipe.id)
- Instead of relying on the automatically generated index the
delHandler now has to find the correct item in the object. The shortest way of doing this seems to be
let recipesCopy = this.state.recipes.slice()
let index = recipesCopy.findIndex(x=>x.id === id)
- Additionally there has to be a unique id generated for each new recipe added to the list, so it seems adding a
currentId pair to
this.state which gets incremented by 1 every time a new recipe item is created should serve well as source for the unique ids