diff --git a/content/docs/faq-functions.md b/content/docs/faq-functions.md index 8f708c7f..0dcbe3c3 100644 --- a/content/docs/faq-functions.md +++ b/content/docs/faq-functions.md @@ -99,13 +99,73 @@ render() { You can use an arrow function to wrap around an event handler and pass parameters: ```jsx -class Foo extends Component { - handleClick (name) { - console.log('Clicked ' + name) + this.handleClick(id)} /> +``` + +This is equivalent to calling `.bind`: + +```jsx + +``` + +#### Example: Passing params using arrow functions + +```jsx +class Component extends React.Component { + state = { + justClicked: 0, + items: Array.from({length: 5}, (_, i) => i) } - render() { - const name = 'My Button' - return + + handleClick = i => this.setState({ justClicked: i }) + + render () { + return ( +
+ Just clicked: {this.state.justClicked} +
    + { this.state.items.map(i => +
  • this.handleClick(i)}> + Item: {i} +
  • + ) } +
+
+ ) + } +} +``` + +#### Example: Passing params using data-attributes + +Alternately, you can use DOM APIs to store data needed for event handlers. Consider this approach if you need to optimize a large number of elements or have a render tree that relies on React.PureComponent equality checks. + +```jsx +class Component extends React.Component { + state = { + justClicked: 0, + items: Array.from({length: 5}, (_, i) => i) + } + + handleClick = event => { + this.setState({ + justClicked: event.target.dataset.i + }) + } + + render () { + return ( +
+ Just clicked: {this.state.justClicked} +
    + { this.state.items.map(i => +
  • + Item: {i} +
  • + ) } +
+
+ ) } } ```