c.casci
c.casci

Reputation: 51

React behavior triggers all buttons on render

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

Upvotes: 0

Views: 433

Answers (1)

c.casci
c.casci

Reputation: 51

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.

Upvotes: 2

Related Questions