Eugene Podoliako Eugene Podoliako - 1 month ago 10
React JSX Question

Reaсt onClick execute all onClick in the elemt

Hi I have the followig code in my component:

<ul className="nav navbar-nav">
<li className="active" onClick={this.props.resetInfoAndError(1)}><Link to="/owner.html">Main<span className="sr-only">(current)</span></Link></li>
<li onClick={this.props.resetInfoAndError(2)}><Link to="/carwash">Second</Link></li>
</ul>


this.props.resetInfoAndError(elemet)
is function that trasfer to component through redux container (
mapDispatchToProps
)

const mapDispatchToProps = (dispatch) => {
return {
saveInfo: (info) => {
dispatch(changeInfo(info))
},

resetInfoAndError: (a) => {
dispatch(changeInfo(a))
}
}
}


I installed redux logger and press on the one
li
tag and see in console that why function is call in both tags (with 1 and 2 param):

enter image description here

Can you explaim why it heppens and how to fix it?

Answer

Don't call the onclick during the render. Use a wrapper function like below.

<ul className="nav navbar-nav">
    <li className="active" onClick={() => this.props.resetInfoAndError(1)}><Link to="/owner.html">Main<span className="sr-only">(current)</span></Link></li>
    <li onClick={() => this.props.resetInfoAndError(2)}><Link to="/carwash">Second</Link></li>
</ul>