Krizzu Krizzu - 1 year ago 81
React JSX Question

Reactjs - Need to bind a onClick handler twice?

Coming from Vue.js (two way data flow) I have question about react one way data flow - I have a Parent that have a handler for its child onClick:

<div className="recipe-container">
<button onClick={this.toggleRecipeList.bind(this)}>Show Recipes</button>
<RecipeList showRecipe={this.showRecipe} list={this.state.recipes} />
</div>


So, I pass
showRecipe
handler, which has only one parameter (and simply just logs it to the console).

My
RecipeList
looks like this (stateless func):

return (<ul className='recipe-list-bottom'>
{
props.list.map((rec, key) => {
return <li onClick={props.showRecipe(rec)} key={key}>{rec.title}</li>
})
}

</ul>)


I tried to launch
showRecipe(rec)
to have the current
rec
object as argument. Although I recive what I want, the handler is being fired from a
button
which is a sibling of
RecipeList
.

I manage to get it working by adding
onClick={props.showRecipe.bind(null,rec)}
to
li
element, but I find it really dirty way to do so.

Am I missing something? I thought
showRecipe(rec)
would be enough to get what I wanted. Why
showRecipe(rec)
is being fired with
this
set to
button
?

Answer Source

I think that your second snippet has a classic error:

return (<ul className='recipe-list-bottom'>
        {
            props.list.map((rec, key) => {
                return <li onClick={props.showRecipe(rec)/*here*/} key={key}>{rec.title}</li>
            })
        }

    </ul>)

You are assigning the result of calling to showRecipe to the onCLick parameter, not the function itself. The bind solutions works, but if you want to pass the parameter rec without using bind you need to wrap the call:

return (<ul className='recipe-list-bottom'>
        {
            props.list.map((rec, key) => {
                return <li onClick={()=>props.showRecipe(rec)} key={key}>{rec.title}</li>
            })
        }

    </ul>)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download