0

I'm stuck with a problem on my ReactJS code causes an onClick error that I can't understand.

<button onClick={this.apiGetProductPicture(this.props.categorie)}>{this.props.name}</button>

If I write it like this (with no parameters it works)

<button onClick={this.apiGetProductPicture()}>{this.props.name}</button>

But with parameters, the function works when I load the page and do not need to click...

An example of how I give the parameter.

<ProductItem name={"Boulangerie"} categorie={0} />

I already search but don't understand why function start without permission.

Function:

    apiGetProductPicture(i) {
    console.log('apiGetProductPicture');
    var json = myApiGet('https://******')
        // TODO do something with the data
        .then(json => this.setState({ pictures: json.content.categories[1].background }))

        .catch(error => console.log('home2', error));
}
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Sneatyx
  • 21
  • 4

1 Answers1

0

you have to give the reference of a function on the onClick:

So you have to write something like it :

apiGetProductPicture= (i) => () => {
    i = 0;
    console.log('apiGetProductPicture');
    var json = myApiGet('https://******')
        // TODO do something with the data
        .then(json => this.setState({ pictures: json.content.categories[1].background }))

        .catch(error => console.log('home2', error));
}
benjamin Rampon
  • 1,316
  • 11
  • 18