How to conditionally add or not onClick on a div in react?

JavascriptReactjs

Javascript Problem Overview


I would like to know if it is possible to set onClick on a div element in react based on the value of a property in my case canClick.

I am aware that I can check this.state directly in handler instead I am looking for a solution to be implemented inside render.

...
handler(){
}

render() {
  const { canClick} = this.state
  return (
    <div onClick={this.handler}>hello</div>
  )
}
...

Javascript Solutions


Solution 1 - Javascript

Put the condition like this:

onClick={canClick ? this.handler : undefined }

Working Code:

class App extends React.Component {
  
   _click(){
      // it will not print the value
      console.log('yes');
   }

   render(){
      return (
        <div>
          <div onClick={false ? this._click : undefined }>Click</div>
        </div>
      )
   }
}

ReactDOM.render(<App />, document.body);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Solution 2 - Javascript

You can treat the elements attributes (like onClick) as object properties. Use the spread operator to only on condition, spread the onClick:

<div
  {...(canClick && { onClick: this.handler })}
>
  hello
</div>

Solution 3 - Javascript

<div onClick={canClick ? this.handler : undefined} />

If you opt for a different falsy value instead of undefined in this ternary (i.e. false or null) React (currently) throws the following warning:

"If you used to conditionally omit it with onClick={condition && value}, pass onClick={condition ? value : undefined} instead."

Edit 2020-01-05: only false throws the above error (React source code here).

Solution 4 - Javascript

Yes you can with ternaru operator, which evaluates the left side as boolean and if true it executes the right side or the fallback.

<div onClick={() => canClick ? this.handler() : () => false }>hello</div>

https://stackblitz.com/edit/react-uwzn4n

Solution 5 - Javascript

You can use this

{...(condition ? { onClick: () => {handleClick()}} : {})}

Solution 6 - Javascript

You can add Conditional Operator for this kind of purpose.

handler(){
}
render() {
  const { canClick} = this.state
  return (
      <div>
       {
        (canClick) ? 
         (<div onClick={this.handler}>clickble</div>) : 
         (<div>not clickble</div>)
        }
      </div>
    
  )
}

Here is document example for that reactjs.org/docs/conditional-rendering

Solution 7 - Javascript

This is how I would do it:

onClick={(canClick && this.handler) || null}

Solution 8 - Javascript

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
handler(){
}    
render() {    
const { canClick} = this.state    
return (
    <div onClick={()=>{canClick&&this.handler()}}>hello</div>
  )
}

Solution 9 - Javascript

Let's say you have a function called handleClick() and want to make it available when current is bigger than one, been current an integer variable, then you can do something like so:

onClick={current > 1 ? handleClick : null}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRadexView Question on Stackoverflow
Solution 1 - JavascriptMayank ShuklaView Answer on Stackoverflow
Solution 2 - JavascriptjorbuedoView Answer on Stackoverflow
Solution 3 - JavascripttomvalorsaView Answer on Stackoverflow
Solution 4 - JavascriptMosè RaguzziniView Answer on Stackoverflow
Solution 5 - JavascriptrecepdemirelView Answer on Stackoverflow
Solution 6 - JavascriptBinit GhetiyaView Answer on Stackoverflow
Solution 7 - JavascriptMarlon Allan SupetranView Answer on Stackoverflow
Solution 8 - JavascriptMohammadHosseinView Answer on Stackoverflow
Solution 9 - JavascriptGassView Answer on Stackoverflow