I am dynamically rendering react components as:
{map.call(this.state.text, (c, i) => (<Char
click={() => this.deleteCharHandler(i)}
charVal={c}
key={i}/>))}
Where there render method of the Char component is:
render() {
return(
<div className="char" onClick={this.props.click}>
{this.props.charVal}
</div>
)
That works and deleteCharHandler is appropriately called with the correct value of i.
However, I would like to avoid having to pass the handler function as a prop. After all, onClick of the div is simply executing the click property, which is an anonymous function calling deleteCharHandler. I tried to refactor as:
{map.call(this.state.text, (c, i) => (<Char
onClick={() => this.deleteCharHandler(i)}
charVal={c}
key={i}/>))}
Thus adding a react event listener to the Char element. And removed the onClick listener from the div in the Char component.
...And it doesn't work.
Why? Am I not just moving the onClick listener one level up?
Chars representation in the dom is what gets returned from itsrendermethod and in there you can add DOM event handlers. TheonClickonCharis just another property passed down, it has no functionality on its own.