Reputation: 5200
I have a React component built like so, that takes in a callback function from its Parent component. When the onClick fires, it calls the callback with a value from the items being mapped over:
class Child extends Component {
static propTypes = {
...
}
render = () => {
return (
<div>
{this.props.data.map((el, idx) => {
return <section onClick={() = this.props.cb(el.val)}></section>
}
)}
</div>
);
}
}
What I'm wondering is how I can accomplish passing a value from that map
to the callback without using this syntax () => this.props.cb(item.val)
or binding a value to the callback. I can't just pass the callback to onClick
because it fires immediately with the value, either.
The current syntax works but breaks the rules I have setup in my linter.
Upvotes: 1
Views: 330
Reputation: 62793
An alternative to binding in render
is breaking out a new component which takes the callback and the value to be passed:
class Section extends React.Component {
handleClick = () => {
this.props.onClick(this.props.val)
}
render() {
return <section onClick={this.handleClick}></section>
}
}
(I would suggest just disabling that lint rule, though)
Upvotes: 2