How to pass parameters on events in React?

Asked

Viewed 2,934 times

4

Assuming the code below (line 15):

import React from 'react'
import ReactDOM from 'react-dom'

const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

function App() {
  function handleClick(item) {
    alert(`Você clicou no item ${item}!`)
  }

  return (
    <>
      {items.map((item) => (
        // Note na linha abaixo, em que uso uma arrow function:
        <button key={item} onClick={() => handleClick(item)}>
          Item {item}
        </button>
      ))}
    </>
  )
}

ReactDOM.render(<App />, document.getElementById('root'))

Note that I need to pass an argument to mine Handler event (as I did on line 15). I used a Arrow Function, calling the function handleClick, passing the desired argument (in the example, item).

Currently, I know there are two ways to do this:

  • Using Arrow functions, as shown in the example above ({() => eventHandler(...args)});
  • Using Function.prototype.bind ({this.handleClick.bind(this, ...args)}).

However, according to the documentation, these two options create a new function at each render, which may affect performance in certain cases.

These warnings can be seen here and here.

So the question is, assuming that it is necessary to pass an argument of the render, there is some way to do it without after a performance (since the React documentation only cites the two examples)?

1 answer

4


You need to create another component and pass the item as props:

import React from 'react'
import ReactDOM from 'react-dom'

const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

class MyButton extends React.Component {
    constructor() {
        this.handleClick = this.handleClick.bind(this);
    }

    function handleClick() {
        alert(`Você clicou no item ${this.props.item}!`)
    }

    render() {
        return (
            <button onClick={this.handleClick}>
                Item {this.props.item}
            </button>
        );
    }
}

function App() {
  return (
    <div>
      {items.map((item) => (
        <MyButton item={item} />
      ))}
    <div/>
  )
}

ReactDOM.render(<App />, document.getElementById('root'))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.