Home > Software design >  Why is an array that is passed correctly via props returning undefined?
Why is an array that is passed correctly via props returning undefined?

Time:11-10

I'm trying to load each string of an array of strings in a <li> html tag by passing this array via props:

<CardItem
  src='https://static.news...koinex-banner.png'
  text='my text'
  label='Adventure'
  path='/products'
  description={["someText1", "someText2", "someText3", "someText4"]}
/>
function CardItem(props) {
  return (
    <>
      <li className='cards__item'>
        <Link className='cards__item__link' to={props.path}>
          <figure className='cards__item__pic-wrap' data-category={props.label}>
            <img
              className='cards__item__img'
              alt='Travel Image'
              src={props.src}
            />
          </figure>
          <div className='cards__item__info'>
            <h5 className='cards__item__text'>{props.text}</h5>
          </div>
          <CardDescription description={props.description} />
        </Link>
      </li>
    </>
  );
}

export default CardItem;
function CardDescription(props) {
  return (
      <div>
          <ul>
              <li>{props.description[0]} </li>
          </ul>
      </div>
  )
}

export default CardDescription

And I'm getting

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

I'm not sure why props.description prop is returning undefined.

Also, this TypeError seems to only be happening with the props.description prop.

CodePudding user response:

well, that's probably because during the mounting of the three the description prop could be undefined, you could avoid this error by doing this props?.description[0], also if you want to render all the values in the array inside the CardDescrition component you could do this

   props?.description.map((item) => (<li>{item}</li>))

CodePudding user response:

Your code is misspelled CardDescrition to CardDescription

Try:

{props.description ? <CardDescription description={props.description} /> : ''}

and in description:

function CardDescription(props) {
    return (
        <div>
            <ul>
                {props.description.map(des => <li>des</li>)}
            </ul>
        </div>
    )
}

please find the minimal repo I created:

https://github.com/snake-py/so-help-react-card

Explanation:

I try to explain from what I understand what is happening there.

When Carditems mounts it seems even though you hard code the values, that they are not passed on the initial render. Hence, the ternary check if the props include the description array.

I am guessing now why that is:

Perhaps because they are inside a wrapper component of Link. If you remove the Link component the code should work without the initial check.

  • Related