Oops! Looks like the image property is undefined in React and causing a TypeError

Something seems to be going wrong with the Product.js file. This is where I am encountering an error related to finding the ID of the product that is being clicked on from data.js. The issue appears to be in the title section, and I'm struggling to figure out why the data is not being retrieved from data.js. Can someone offer assistance?

import React from 'react';
import data from '../data';
import { Link } from 'react-router-dom';
    
function Product(props) {
    console.log(props.match.params.id);
    const product = data.bags.find(x => x._id === props.match.params.id);
    return <div>
        <div className="back-to-result">
            <Link to="/">Back to result</Link>
        </div>
        <div className="details">
            <div className="details-image">
                <img src={product.image} alt="product" /> // this is where the error occurs
            </div>
            <div className="details-info">
                <ul>
                    <li>
                        <h4>{product.brand}</h4>
                    </li>
                    <li>
                        {product.name}
                    </li>
                    <li>
                        {product.ratings} Stars ({product.reviews} Reviews)
                    </li>
                    <li>
                        Price: <b>₹{product.price}</b>
                    </li>
                    <li>
                        Description:
                        <div>
                            {product.description}
                        </div>
                    </li>
                </ul>
            </div>
            <div className="details-action">
                <ul>
                    <li>
                        Price: ₹{product.price}
                    </li>
                    <li>
                        Status: {product.status}
                    </li>
                    <li>
                        Qty: <select>
                            <option>1</option>
                            <option>2</option>
                            <option>3</option>
                            <option>4</option>
                            <option>5</option>
                        </select>
                    </li>
                    <li>
                        <button className="button">Add to cart</button>
                    </li>
                </ul>
            </div>
        </div>

    </div>
}

export default Product;

I should be getting the required data from data.js as this is the Redux store where all the necessary data has been stored.

 export default {
            bags: [
                {
                    _id: '1',
                    category: 'watch',
                    name: "Bags",
                    brand: "Hublot",
                    price: 8000,
                    image: "/images/1.jpg",
                    ratings: 4.5,
                    reviews: 10
                },
                {
                    _id: '2',
                    category: 'bags',
                    name: "Watch",
                    brand: "Ulysse Nardin",
                    price: 10000,
                    image: "/images/2.jpg",
                    ratings: 3.5,
                    reviews: 12
                },
                {
                    _id: '3',
                    category: 'bags',
                    name: "Watch",
                    brand: "Tissot",
                    price: 4000,
                    image: "/images/3.jpg",
                    ratings: 5,
                    reviews: 24
                },
                {
                    _id: '4',
                    category: 'sunglasses',
                    name: "Watch",
                    brand: "Hublot",
                    price: 8000,
                    image: "/images/1.jpg",
                    ratings: 1.4,
                    reviews: 42
                },
                {
                    _id: '5',
                    category: 'bags',
                    name: "Watch",
                    brand: "Ulysse Nardin",
                    price: 10000,
                    image: "/images/2.jpg",
                    ratings: 3.7,
                    reviews: 14
                },
                {
                    _id: '6',
                    category: 'watch',
                    name: "Watch",
                    brand: "Tissot",
                    price: 4000,
                    image: "/images/3.jpg",
                    ratings: 4,
                    reviews: 17
                }
            ]
        }

Answer №1

When you use the line:

const product = data.bags.find(x => x.id === props.match.params.id);

it is possible for the product to be undefined.

If this happens, you won't be able to access the expected fields, resulting in an error.

To prevent this error, add

if (!product) return <p>Product Not Found</p>
after that line. This will exit early if the product is undefined or empty, but will continue and render normally if a product is found.


Additionally, make sure your find function is targeting the correct field name. In your data example, the items have the _id field instead of the id field, so your find should be:

data.bags.find(x => x._id === props.match.params.id)

Answer №2

To ensure that your details section functions properly, wrap it in this code block to check if the product variable is defined before attempting to access its properties.

{product &&

    (<div className="details">
        <div className="details-image">
            <img src={product.image} alt="product" /> // encountering an error here
        </div>
        <div className="details-info">
            <ul>
                <li>
                    <h4>{product.brand}</h4>
                </li>
                <li>
                    {product.name}
                </li>
                <li>
                    {product.ratings} Stars ({product.reviews} Reviews)
                </li>
                <li>
                    Price: <b>₹{product.price}</b>
                </li>
                <li>
                    Description:
                    <div>
                        {product.description}
                    </div>
                </li>
            </ul>
        </div>
        <div className="details-action">
            <ul>
                <li>
                    Price: ₹{product.price}
                </li>
                <li>
                    Status: {product.status}
                </li>
                <li>
                    Qty: <select>
                        <option>1</option>
                        <option>2</option>
                        <option>3</option>
                        <option>4</option>
                        <option>5</option>
                    </select>
                </li>
                <li>
                    <button className="button">Add to cart</button>
                </li>
            </ul>
        </div>
    </div>)
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for altering the orientation of documents in Docusaurus

Instead of having a landing page on my Docusaurus 2 site, I redirect to the first .md file in the sidebar following instructions from this link: Now, I'm looking to create a multi-language website with English and Persian. The Persian version needs t ...

Is there a way to retrieve the text content from a span element using JavaScript?

Revised for better organization and explanation of the question Hello, I am new to web programming so please bear with me. My question is about extracting customer information from the following code snippet: <span class="tag-element-content" ...

Retrieve a React element that incorporates a value from an array based on a separate array of integers

I am working with two arrays that contain integers and strings like the following: let intArr = [4,3,2,1] let player = ['a','b','c','d','e','f','g','h','i','j&ap ...

What is the best way to align a modal with a layout when it appears far down the components hierarchy?

Struggling with creating a React modal and facing some issues. Let's consider the structure below: React structure <ComponentUsingModal> <Left> <ButtonToActivateModal> ... </ButtonToActivateModa ...

Problematic situation when using ng-repeat with dynamic ng-include and template variables scope conflict

When utilizing ng-repeat with dynamic ng-include that includes variables, the variables are not being properly recognized. Take a look at this code snippet. Here is the main HTML code: <table style> <tr> <th>Student</th> ...

Issue with sliding panel not working smoothly in Internet Explorer

Is there a way to remove the added margin when opening the info slide panel? The issue seems to only occur in IE (using the IE tab plugin for Firefox) and in IE7 and IE8, the tooltip does not display. Thank you for any assistance. Site Link ...

What is the best way to send the value of a Select component from a child to a parent component in

Users have the ability to select a category, triggering the appearance of another dropdown menu based on their selection. I have created a separate component in a different file (.js) to handle this second dropdown. While I can see the data, I am wondering ...

Ensure that the Y scale domain minimum for the stacked bar chart is set to a value greater than zero to prevent overflow on

I am completely new to utilizing D3 for data visualization and I'm currently struggling with adjusting my stacked bar chart when the domain does not start at 0 or a specific maximum value. I've experimented with various solutions, but nothing see ...

Add the Selected Value to the Title

Is there a way to dynamically add the selected value from each select element to its corresponding heading without requiring user interaction? I need this to happen as soon as the page loads. Here is an example in a jsfiddle https://jsfiddle.net/dqfvyvdt/2 ...

Error With IOS Safari Causes React Website to Display Blank Page

After creating a single page website using React, I encountered an issue where the site would display a white page error on IOS devices while working fine on Android and Windows devices. Despite trying several solutions, the problem persisted. Interestingl ...

What happens if the document.ready function fails to execute?

Many JavaScript developers have encountered a situation where page elements are not available in the document.ready event because it fires too soon, especially when most parts of the page are loaded dynamically with AJAX. Currently, I am working with Drupa ...

How can I display a specified start and end time for a lengthy video file using either react js or node js?

Picture this scenario: You are faced with a blank page featuring two empty fields where users are encouraged to input timestamps in the format below: start: 00:20:21.330 end: 00:22:31.330 On the page, there is a start button. Upon clicking it, a trimmed ...

Place an element in relation to the vertical size of a div that includes written content

Currently, I am working on implementing a button with a popup that appears underneath it when the user hovers over it. The specific requirements for this setup are: The size of the button should not affect the size of the popup The popup should always be ...

Excessive gap following the footer

I'm facing an issue where my footer has extra space at the end which is also in the background color of the page. How can I resolve this? footer { text-align: center; background-color: orange; margin-bottom: -200px; height: 5em; } ...

Tips for sequentially arranging and rearranging an array of numbers, even when duplicates are present

Encountered a perplexing issue that has me scratching my head in an attempt to visualize a solution. Currently, I am working with an array of objects that appears as follows: let approvers = [{order:1, dueDate: someDate},{order:2, dueDate: someDate}, ...

Encountered issue with useFieldArray append in react-hook-form (Unable to access properties of null like 'focus')

I encountered an error with the Material-UI Select component (specifically, "Cannot read properties of null (reading 'focus')") when attempting to call the append function from the useFieldArray hook. You can access the problematic code in this ...

`Nginx with a touch of material design`

Currently, I'm in the process of implementing material design UI on a functioning web application. The application utilizes Nginx, PHP, and PostgreSQL. While I have proficiency in PHP and PostgreSQL to ensure the functionality (code composed in notepa ...

Avoiding the ESLint error of missing return type in a React TypeScript function

My JavaScript function looks like this: export default () => ({ root: css` background-color: hotpink; margin-bottom: 1.45rem; `, }); However, ESLint is raising a complaint: Missing return type on function.eslint@typescript-eslint/explicit-m ...

What is the method for adding multiple lines to my tooltip content in Material UI IconButton?

I am working on implementing Material UI's IconButton component with a tooltip attribute. The issue I am facing is that my tooltip content is quite lengthy. Is there a way to display the tooltip text on multiple lines instead of having it displayed in ...

Is there a way to attach a canvas image to an email using VB.NET?

In my project, I have successfully converted an SVG to a canvas image using canvg, then converted it to a bytearray in vb.net on the client side. I saved the image to a folder on my server in order to attach it to an email: Protected Sub Button1_Clic ...