Last active
April 1, 2016 13:58
-
-
Save samsch/9893a183e5183ce1c577c9f63522d558 to your computer and use it in GitHub Desktop.
How to solve binding functions which need a index or value (e.g., buttons in something that is .map()ed.)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const React = require('react'); | |
const ReactDOM = require('react-dom'); | |
class Component extends React.Component { | |
constructor(props) { | |
super(props); | |
this.handleButton = this.handleButton.bind(this); | |
} | |
handleButton(ev) { | |
//name needs to be cast to an int since attributes are all strings. | |
this.props.handler(+ev.target.name); | |
} | |
render() { | |
<ul> | |
{this.props.list.map((item, index)=>{ | |
return ( | |
<li> | |
<button name={index} onClick={this.handleButton}>{item.label}</button> | |
</li> | |
); | |
})} | |
</ul> | |
} | |
} | |
module.exports = Component; | |
const arr = [ | |
{ | |
label: 'button 1', | |
}, | |
{ | |
label: 'button 2', | |
}, | |
//... | |
]; | |
const doImportantThingBasedOnClickedButton = function(buttonIndex) { | |
//stuff | |
} | |
ReactDOM.render( | |
<Component list={arr} handler={doImportantThingBasedOnClickedButton} />, | |
renderTarget | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment