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.

export const DISHES = [
  {
    id: 0,
    name: "Uthappizza",
    image: "assets/images/uthappizza.png",
    category: "mains",
    label: "Hot",
    price: "4.99",
    comments: [
      {
        id: 0,
        rating: 5,
        comment: "Imagine all the eatables, living in conFusion!",
        author: "John Lemon",
        date: "2012-10-16T17:57:28.556094Z"
      },
      {

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

import { DISHES } from "../shared/dishes";
class Main extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dishes: DISHES,
      selectedDish: null
    };
  }

  onDishSelect(dishId) {
    this.setState({
      selectedDishId: dishId
    });
  }

  render() {
    return (

          <DishDetail
            dish={
              this.state.dishes.filter(
                dish => dish.id === this.state.selectedDishId
              )[0]
            }


    );
  }
}

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

class DishDetail extends Component {
  constructor(props) {
    super(props);
    this.renderComments = this.renderComments.bind(this);
  }

  renderComments(comments) {
   return (
    .....
    );
  }
  render() {
    return (
          <div className="col-12 col-md-5 m-1">
               /*here is the problem*/
            {this.renderComments(this.props.dish.comments)}
          </div>

    );
  }
}

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 :

this.props.dish && this.renderComments(this.props.dish.comments)

Component code

import React, { Component } from 'react';

class DishDetail extends Component {
  constructor(props) {
    super(props);
    this.renderComments = this.renderComments.bind(this);
  }

  renderComments(comments) {
       return comments.map((comment)=> {
         return(
           <p>
              {comment.comment}
           </p>
         )
       })
  }
  render() {
    return (
          <div className="col-12 col-md-5 m-1">
            {this.props.dish && this.renderComments(this.props.dish.comments)}
          </div>

    );
  }
}

export default DishDetail;

here is a complete stackblitz

Reference :

Array filter in javascript

Advertisement