Skip to content
Advertisement

how to fix “Cannot read property ‘comments’ of undefined” in react

I am extracting array “comments” from an array of objects and when I trying to pass this array to a function I get this error “Cannot read property ‘comments’ of undefined”

here is a snippet from my code.

JavaScript

in main class, I succeeded to get from DISHES array the right element

JavaScript

here I tried to parse “comments” but I couldn’t even to pass it to the function “renderComments” , but when I try to pass “this.props.dish” only it works fine

JavaScript

Advertisement

Answer

You are getting that error because this.state.selectedDishId is undefined and therefore the filter doesn’t find a match.

You can add a check before going in the renderComments function like below :

JavaScript

Component code

JavaScript

here is a complete stackblitz

Reference :

Array filter in javascript

Advertisement