I
I
IDONTSUDO2019-11-12 17:32:29
React
IDONTSUDO, 2019-11-12 17:32:29

React OnClick fun is udefined?

I have such a State. And I have to render it through map and Object.keys.
5dcac11da7332378637165.png

<button onClick={this.handleClick} >Удалить</button> //отлично работает
                {manageList.map((manage, i) =>( 
                    <>
                     <div>
                    {Object.keys(manage.UserBy).map(function(key) {
                  
                      if(key == "id"){
                        return  <button onClick={this.handleClick} >Удалить</button>  //не работает
                      }
                      return <> <div>{manage.UserBy[key]} {manage.price}%</div> </>
                      })}
                     </div>
                    </>))}

//функция 
handleClick(){
    console.log(200)
}

The error that I'm getting.
TypeError: Cannot read property 'handleClick' of undefined

What could be the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2019-11-12
@IDONTSUDO

Object.keys(manage.UserBy).map(function(key) {
replace it with an arrow function, since ordinary functions have their own this, which is different from the context in which they are called, and therefore does not work. PS But for good, I would rewrite the whole piece like this:

{Object.entries(manage.UserBy).map(([key, value]) => 
  key == "id" 
   ? <button onClick={this.handleClick} >Удалить</button>  
   : <div>{`${value} ${manage.price}%`}</div> 
)}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question