Skip to content

Commit bac965e

Browse files
committed
add example using data-attributes for event handler data
1 parent 0143515 commit bac965e

File tree

1 file changed

+66
-6
lines changed

1 file changed

+66
-6
lines changed

content/docs/faq-functions.md

Lines changed: 66 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -99,13 +99,73 @@ render() {
9999
You can use an arrow function to wrap around an event handler and pass parameters:
100100

101101
```jsx
102-
class Foo extends Component {
103-
handleClick (name) {
104-
console.log('Clicked ' + name)
102+
<Element onClick={() => this.handleClick(id)} />
103+
```
104+
105+
This is equivalent to calling `.bind`:
106+
107+
```jsx
108+
<Element onClick={this.handleClick.bind(this, id)} />
109+
```
110+
111+
#### Example: Passing params using arrow functions
112+
113+
```jsx
114+
class Component extends React.Component {
115+
state = {
116+
justClicked: 0,
117+
items: Array.from({length: 5}, (_, i) => i)
105118
}
106-
render() {
107-
const name = 'My Button'
108-
return <button onClick={() => this.handleClick(name)}>Click Me</button>
119+
120+
handleClick = i => this.setState({ justClicked: i })
121+
122+
render () {
123+
return (
124+
<div>
125+
Just clicked: {this.state.justClicked}
126+
<ul>
127+
{ this.state.items.map(i =>
128+
<li onClick={() => this.handleClick(i)}>
129+
Item: {i}
130+
</li>
131+
) }
132+
</ul>
133+
</div>
134+
)
135+
}
136+
}
137+
```
138+
139+
#### Example: Passing params using data-attributes
140+
141+
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.
142+
143+
```jsx
144+
class Component extends React.Component {
145+
state = {
146+
justClicked: 0,
147+
items: Array.from({length: 5}, (_, i) => i)
148+
}
149+
150+
handleClick = event => {
151+
this.setState({
152+
justClicked: event.target.dataset.i
153+
})
154+
}
155+
156+
render () {
157+
return (
158+
<div>
159+
Just clicked: {this.state.justClicked}
160+
<ul>
161+
{ this.state.items.map(i =>
162+
<li data-i={i} onClick={this.handleClick}>
163+
Item: {i}
164+
</li>
165+
) }
166+
</ul>
167+
</div>
168+
)
109169
}
110170
}
111171
```

0 commit comments

Comments
 (0)