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.
Advertisement
Answer
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.