Skip to content
Advertisement

ReactJS – TypeError: Cannot read property ‘name’ of undefined but it is

I have a map function that is supposed to take the data from an list I’ve created and show it to the user but it give me a typerror whenever I try to do that, here’s my map function:

{product.map((item, idx)=>
            <div key={idx}>
                    <h3 className='productName'>{item[idx].name}</h3>
                    <div className='productImageContainer'>
                        <img src={item[idx].image}></img>
                    </div>
                    <span className='productPrice'><strong>${item[idx].Price}.00</strong></span>
                    <br></br>
                    <Button className='removeProductButton' variant='danger'><MdCancel></MdCancel> Remove</Button>

            </div>)}

And here’s the piece of code where I attach the items to the array:

    const [product, getProduct]= useState([])
const getProducts=()=>
{
    let X = JSON.parse(localStorage.getItem('products'))
    getProduct([...product, X])
}

I get the following error: “TypeError: Cannot read property ‘name’ of undefined”, I’ve tried manually console logging each element of the list and it is definitely not undefined, why is that happening and how can I fix it?

Advertisement

Answer

You can access the name property directly on item like so:

<h3 className='productName'>{item.name}</h3>

item is the current element that is being processed in your list.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement