Home > Back-end >  TypeError: Cannot read properties of undefined (reading 'img') React
TypeError: Cannot read properties of undefined (reading 'img') React

Time:10-08

Please Guys i need Help, i got this error when i am compiling the code. i put items in a file data.js and it is working for others products but for this One i don't know what i am missing.

import React from 'react'
import styled from 'styled-components'
import FavoriteBorderOutlinedIcon from '@material-ui/icons/FavoriteBorderOutlined';
import SearchIcon from '@material-ui/icons/Search';
import ShoppingCartOutlinedIcon from '@material-ui/icons/ShoppingCartOutlined'

const Product = ({items}) => {
    return (
        <Container>
        
            <Circle />
            
            <Image src={items.img} />
            
            <Info>
                <Icon>
                    <ShoppingCartOutlinedIcon />
                </Icon>
                <Icon>
                    <SearchIcon />
                </Icon>
                <Icon>
                    <FavoriteBorderOutlinedIcon />
                </Icon>
            </Info>
    </Container>
    )
}

export default Product;



const Container = styled.div`
    flex: 1;
    margin: 5px;
`;
 
const Circle = styled.div``;

const Image = styled.img``;

const Info = styled.div``;

const Icon = styled.div``;

CodePudding user response:

Try checking for the existence of the image before you send it to src

items && test.img ? test.img : "https://www.example.com/example.png"

So just add it to your styled image:

 <Image src={items && test.img ? test.img : "https://www.example.com/example.png"} />

CodePudding user response:

You have to check if your items props get correctly image or img source. For that You have to give that component from where you send items as props.

Here you can check if your items has img property. For that console the items in useEffect.

import {useEffect} from "react"

const Product = ({items}) => {
    const useEffect = () => {
      console.log(items)
    }
    return (
        <Container>
        
            <Circle />
            
            <Image src={items.img} />
            
            <Info>
                <Icon>
                    <ShoppingCartOutlinedIcon />
                </Icon>
                <Icon>
                    <SearchIcon />
                </Icon>
                <Icon>
                    <FavoriteBorderOutlinedIcon />
                </Icon>
            </Info>
    </Container>
    )
}

export default Product;

In that way you can confirm your items has a img property.

  • Related