D
D
DeniSidorenko2020-12-14 07:48:51
React
DeniSidorenko, 2020-12-14 07:48:51

How to make a function execute only on click in setState?

hello i have this code

this.setState({
  Products:  products.map((product, index) => {
    return(
      <div className="catalog-item" onClick="console.log('click)" key={index} data-id={product._id}>
        <div className="catalog-item__top">
          <h4>{product.name}</h4>
        </div>
      </div>
      )
  })
})


The problem is that onClick is executed immediately when rendering (the function is not available further)
How to make it not be executed when rendering, but only when clicking on an object
Thank you

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2020-12-14
@DeniSidorenko

First, all this is good in render.
Second, onClick={() => yourHandler(yourArgs)}. But apparently you are working with a class component, so yourHandlermake it a class method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question