Skip to main content

onClick tips in React

Passing Arguments to onClick There are times when you need to pass arguments to an onClick function in React but obviously you don't want to immediately invoke the function.

You can do this by using an arrow function in the onClick:

<div className='whatever' onClick={(event) => this.props.jumpTo(index, event)}>
Yadda yadda yadda
</div>

Conditionally have onClick In other cases you may want to render an element in a React component all the time, but only have an onClick if certain conditions are met. You can do this by using a ternary where the condition that should not have an onClick is given null.

<div className='whatever' onClick={x > 1 ? this.props.myFunction : null}>
Yadda yadda yadda
</div>