-1

How do i prevent the OnClick function within the buttom from beeing called whenever the list is rendered?


   {this.state.citylist && this.state.citylist.map((city, index) => 
       <li key={index}>
          {city.name}
          <button type="button" onClick={console.log(city.name)}>Click me</button>
       </li>
   )}

as always, thanks for your help.

  • 10
    You're executing the function immediately. Wrap it in a `callback`: `() => console.log(city.name)` – Dupocas Oct 10 '19 at 12:18

4 Answers4

0

console.log(city.name) is a statement. onClick expects a function.

You can wrap it in a function, inline or declare it elsewhere in the code a and give the reference to onClick.

<button type="button" onClick={() => console.log(city.name)}>Click me</button>
vatz88
  • 2,347
  • 2
  • 14
  • 23
0

An onClick accepts a function as its parameter. Not a function call. So a function that will be called. Which is called a callback.

 onClick={function(){console.log('This will be called')}}

console.log() , is a function call. You're invoking the log method which belongs to the console object.

Kevin.a
  • 3,831
  • 5
  • 37
  • 75
0

OnClick takes a callback/function to be invoked when click event occurrs so add your code inside function and your are good to go

<button onClick={() => console.log(city.name)} >Button</button>
Zohaib Ijaz
  • 19,906
  • 6
  • 35
  • 55
0

You need to wrap it in an annon function. An annon function is a function with no name, and can infact be declared inline:

() => {}

This will work in most cases, but some times you might need to pass arguments inside of it in es5 because you cant make use of lexical 'this'