Search code examples
javascriptreactjsonclicknext.jsreact-props

Passing component props into a string in ReactJS/NextJS


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} + "`);
}

Solution

  • 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>
        );
    }