Skip to content

Instantly share code, notes, and snippets.

@samsch
Last active April 1, 2016 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samsch/9893a183e5183ce1c577c9f63522d558 to your computer and use it in GitHub Desktop.
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.)
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