Uncaught TypeError: items is undefined. Items for Drinks not showing up

157 Views Asked by At

I am trying to create a separate div for my Drinks section but it does not seem to be population and I am getting an uncaught TypeError. I am sure that I have the items defined so I am not sure what's going on.

import React from "react";

const Drinks = ({ items }) => {
  return (
    <div className="section-center">
      {items.map((item) => {
        const { id, title, img, desc } = item;
        return (
          <article key={id} className="drinks-item">
            <img src={img} alt={title} className="photo" />
            <div className="drinks-info">
              <header>
                <h5> {title} </h5>

              </header>
              <p className="item-text">
                {desc.split("\n").map((item, index) => (
                  <React.Fragment key={index}>
                    {item}
                    <br />
                  </React.Fragment>
                ))}
              </p>
              </div>
          </article>
          
        );
      })}
    </div>
  );
};

export default Drinks;

I've spent a number of hours on this but to no avail. If someone could help me, it would be greatly appreciated.

1

There are 1 best solutions below

0
Sean Mizen On

The answer from @iva is good. Here's an alternative if you want to always render the "section-center" div:

(Check that items exists and has length > 0)

import React from 'react';

const Drinks = ({ items }) => {
  return (
    <div className="section-center">
      {items?.length ? (
        items.map(item => {
          const { id, title, img, desc } = item;
          return (
            <article key={id} className="drinks-item">
              <img src={img} alt={title} className="photo" />
              <div className="drinks-info">
                <header>
                  <h5> {title} </h5>
                </header>
                <p className="item-text">
                  {desc.split('\n').map((item, index) => (
                    <React.Fragment key={index}>
                      {item}
                      <br />
                    </React.Fragment>
                  ))}
                </p>
              </div>
            </article>
          );
        })
      ) : (
        <h1> No items to display </h1>
      )}
    </div>
  );
};

export default Drinks;