0

I'm generating a list of persons and 'delete buttons' via map() to be rendered in a React component (passing the mapped list through props and rendering inside a <p> tag).

When react first renders, it triggers all buttonsonClick() and the buttons cease working.

Why this behavior happens, please?

  const deletePerson = (id) => {
    console.log(`deleting id: ${id}`)
  }

  const mappedPersons = persons.map(person => 
    <li key={person.name}>
      {`${person.name} - `}
      {`${person.phone} `}
      <button onClick={deletePerson(`${person.id}`)} value={person.id}>
        delete person
      </button>
    </li>
)

console:

deleting id: 1
deleting id: 2
deleting id: 3
deleting id: 4
deleting id: 5
deleting id: 6
deleting id: 7
deleting id: 8
c.casci
  • 51
  • 8
  • `deletePerson` method should be placed in the `callback` function. Placing `deletePerson()` is function call. – random Jan 28 '20 at 14:46

1 Answers1

2

this answer gets it: React onClick function fires on render

changing the button onClick to:

<button onClick={() => deletePerson(`${person.id}`)} value={person.id}>
        delete person
      </button>

makes map stop calling the function on render.

c.casci
  • 51
  • 8