[Solved] TypeError: Cannot read properties of undefined (reading 'name')

React JS Sharif Ahmed

Problem:

While trying to use the bootstrap modal to display each item on a table when clicked on the view button. We are getting an error like,

TypeError: Cannot read properties of undefined (reading 'name')

The ModalPractice.js is given below,

<tbody>
{food.map((list) => (
   <tr className='align-middle' key={list.id}>
    <td>{list.id}</td>
    <td>{list.name}</td>
    <td>{list.category}</td>
    <td>
        <img alt='' src={list.image} width='100' height='100' />
    </td>
    <td>
	<DetailModal
	   id={list.id}
	   name={list.name}
	   category={list.category}
	   handleShow={handleShow}
	   handleClose={handleClose}
	   show={show}
	   selectedItem={selectedItem}
	 />
    </td>
   </tr>
))}
</tbody>

The DetailModal.js is below:

export const DetailModal = (props) => {
  const {selectedItem, show, handleClose, handleShow, list} = props
  return (
    <div>
      <Modal show={show} onHide={handleClose}>
        <Modal.Header closeButton>
          <Modal.Title>{selectedItem.name}</Modal.Title>
        </Modal.Header>
        <Modal.Body>{selectedItem.category}</Modal.Body>
      </Modal>
      <Button variant='primary' onClick={(e) => handleShow(e, list)}>
        Detail
      </Button>
    </div>
  );
};


Solution:

The error variable showing undefined because a list prop is not passed to the DetailModal. So when trying to use the map function on the list it shows the error. So, the list variable must be passed as props in ModalPractice.js. The ModalPractice.js needs to update like:

<DetailModal
   id={list.id}
   name={list.name}
   category={list.category}
   handleShow={handleShow}
   handleClose={handleClose}
   show={show}
   list={list}
   selectedItem={selectedItem}
/>


Thank you for reading the article. If you have any suggestions please comment below. Your comment is always important to us.