2

I'm very new to React and I'm wondering why I can't set my in-class method without using an arrow function for my component's onClick.

I don't really know how to phrase this question right, so here's the code. In ShopManager.renderItem(), I can't set onClick without using the arrow function. My goal is not to defy the rules of the syntax, I just want to know why/how it works.

import './App.css';
import React from 'react';

class Item extends React.Component{
    constructor(props){
        super(props);
        this.name = props.name;
    }
    render(){
        return <button onClick={this.props.onClick}>{this.name}</button>;
    }
}

class Cart extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            items: [],
            numItems: 0,
            totalCost: 0
        }
    }
    render(){return} //ignore this - irrelevant
}

class ShopManager extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            cart: <Cart />,
            itemsForSale: []
        }
        this.addItemToCart = this.addItemToCart.bind(this);
    }
    addItemToCart(itemName){
        console.log(itemName);
    }
    renderItem(itemName){
        return(
            <Item 
                name={itemName}
                onClick={() => this.addItemToCart(itemName)} //this works
                //onClick={this.addItemToCart(itemName)} //why doesn't this work?
            />
        )
    }
    render(){
        return this.renderItem("Pants");
    }
}

function App(){
    return(
        <ShopManager />
    )
}

export default App;


Owen Kelvin
  • 14,054
  • 10
  • 41
  • 74
asayee0
  • 21
  • 3

0 Answers0