1

I have the following component

import Link from "next/link";
import styles from "./product.module.css";

export default function Product(props) {
  return (
    <div className={styles.product}>
      <Link href={props.link}>
        <img src={props.img} alt={props.name} />
      </Link>
      <Link href={props.link}>
        <h3>{props.name}</h3>
      </Link>
      <span>{props.price}</span>
              <button onClick={handleClick}>
          Add to Bag 
        </button>
    </div>
  );  
}

I am trying to add an onClick named handleClick and for testing, I am trying to run a console log containing the following {props.name} has been added to the basket at a price of {props.price}

However, onClick I receive the following error: TypeError: undefined is not an object (evaluating '_this.props')

What is the process to fix this?

The code for the handleClick function is below.

const handleClick = (e) => {
        console.log(`${this.props.name} + "added to basket at price of " + ${this.props.price} + "`);
}

1 Answer 1

2

In function component, it does not have context about this. Why don't use props as you have used in return function.

export default function Product(props) {
    const handleClick = (e) => {
        console.log(`${props.name} + "added to basket at price of " + ${props.price} + "`);
    }
    
    return (
        <div className={styles.product}>
            <Link href={props.link}>
                <img src={props.img} alt={props.name} />
            </Link>
            <Link href={props.link}>
                <h3>{props.name}</h3>
            </Link>
            <span>{props.price}</span>
            <button onClick={handleClick}>
                Add to Bag
            </button>
        </div>
    );
}
Sign up to request clarification or add additional context in comments.

7 Comments

I tried this initially and it says ReferenceError: Can't find variable: props
Where is function declared? It will work in my edit.
The function is declared in the component/product.js file? Should it be declared on the page that it is called?
By the way, if you want to declare function in somewhere esle, check how access variables in function by concept Closure in js: stackoverflow.com/questions/111102/….
It isn't declared somewhere else, it is declared in the product component @Viet Dinh
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.