'Uncaught TypeError: Cannot read properties of undefined (reading 'comments')

Following is my Dishdetail component in reactjs. It receives props from its parent component and and has a child component named "RenderComments" which renders the comments from the props.

import React from "react";
import { Card, CardImg, CardImgOverlay, CardText, CardBody, CardTitle } from "reactstrap";



    function RenderDish({dish}) {
        if (dish != null) {
            return (
                <Card>
                    <CardImg width="100%" object src={dish.image} alt={dish.name}></CardImg>
                    <CardBody>
                        <CardTitle>{dish.name}</CardTitle>
                        <CardText>{dish.description}</CardText>
                    </CardBody>
                </Card>
            )
        }
        else {
            return (
                <div></div>
            )
        }
    }

    function RenderComments({comments}) {
        let c = [];
        if (comments != null) {
            c = comments.map((element) => {
                return (
                    <li key={element.id}>
                        <p>{element.comment}</p>
                        <p>-- {element.author}, {new Date(element.date).toLocaleDateString("en-us", { year: "numeric", month: "short", day: "2-digit" })}</p>
                    </li>

                )
            });
        }

        return (
            <div>
                <h4>Comments</h4>
                <ul className="list-unstyled">
                    {c}
                </ul>
            </div>
        )
    }
    
    const Dishdetail =(props)=>{
        return (
            <div className="container">
                <div className="row">
                    <div className="col-xs-12 col-md-5 m-1">
                        <RenderDish dish={props.dish}/>
                    </div>
                    <div className="col-xs-12 col-md-5 m-1">
                        <RenderComments comments={props.dish.comments}/>
                    </div>

                </div>
            </div>

        )
    }


export default Dishdetail;

I get this error:"Uncaught TypeError: Cannot read properties of undefined (reading 'comments')"

Since I am a beginner I do not know how to fix this error. Can please someone guide me? Also I would be glad if someone could specify the reason for this error



Solution 1:[1]

please use optional chaining and inspect why comment comes undefined.

comments?.map(() => {
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 diyarovski