Conditionally add an onClick event handler in React

avatar

Borislav Hadzhiev

Fri Apr 22 20222 min read

banner

Photo by Silviu Zidaru

Conditionally add an onClick event handler in React #

Use the ternary operator to conditionally add an onClick event handler in React, e.g. onClick={shouldAddEventHandler ? handleClick : undefined}. The ternary operator returns the value to the left of the colon if the condition is truthy.

App.js
export default function App() { const shouldAddEventHandler = true; const handleClick = event => { console.log('Button clicked'); }; return ( <div> <button onClick={shouldAddEventHandler ? handleClick : undefined}> Click </button> </div> ); }

We used a ternary operator to conditionally add an event handler in React.

If the value to the left of the question mark is truthy, the operator returns the value to the left of the colon, otherwise the value to the right of the colon is returned.

App.js
const result1 = 5 === 5 ? 'yes' : 'no'; console.log(result1); // 👉️ "yes" const result2 = 5 === 10 ? 'yes' : 'no'; console.log(result2); // 👉️ "no"

If the shouldAddEventHandler variable in the example stores a truthy value, the onClick prop on the button gets set to the handleClick function.

Otherwise, the onClick prop gets set to an undefined value.

Setting a prop to an undefined value is the same as not setting it at all.

You might also see examples that use the logical AND (&&) operator to conditionally add an event handler, e.g. <button onClick={shouldAddEventHandler && handleClick}>Click</button>.

The logical AND (&&) operator returns the value to the left if it's falsy, otherwise the value to the right is returned.

This approach should be avoided because it may cause confusing warnings.

The falsy values in JavaScript are: false, null, undefined, 0, "" (empty string), NaN (not a number).

If the value to the left of the logical AND (&&) operator stores a falsy value other than undefined, you'd get a warning because you are setting the onClick prop to an empty string, or false, etc.

Props that point to event handler functions should either be passed a function or undefined, and any other value would show a warning in the Console tab of your developer tools.

Use the search field on my Home Page to filter through my more than 1,000 articles.