0

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} + "`);
}
Mac
  • 108
  • 2
  • 11

1 Answers1

1

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>
    );
}
Viet Dinh
  • 1,871
  • 1
  • 6
  • 18
  • I tried this initially and it says `ReferenceError: Can't find variable: props` – Mac Sep 23 '20 at 16:42
  • Where is function declared? It will work in my edit. – Viet Dinh Sep 23 '20 at 16:45
  • The function is declared in the component/product.js file? Should it be declared on the page that it is called? – Mac Sep 23 '20 at 16:46
  • By the way, if you want to declare function in somewhere esle, check how access variables in function by concept Closure in js: https://stackoverflow.com/questions/111102/how-do-javascript-closures-work#:~:text=Whenever%20a%20function%20is%20declared%20in%20JavaScript%20a%20closure%20is%20created.&text=A%20closure%20is%20created%20when,time%20a%20function%20is%20called. – Viet Dinh Sep 23 '20 at 16:50
  • It isn't declared somewhere else, it is declared in the product component @Viet Dinh – Mac Sep 23 '20 at 16:54
  • I see I needed to declare the function above the return but within the default function! – Mac Sep 23 '20 at 18:15
  • Thank you for the help! – Mac Sep 23 '20 at 18:16