Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

Can you put onClick on a DIV React?

To set an onClick listener on a div element in React:Set the onClick prop on the div. The function you pass to the prop will get called every time the div is clicked. You can access the div as event.

How do you conditionally render a div in React?

Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like if or the conditional operator to create elements representing the current state, and let React update the UI to match them. This example renders a different greeting depending on the value of isLoggedIn prop.

Can you conditionally add attributes to components in React?

You can use any logic and conditionals in order to build the object. You will most commonly use the ternary operator to add conditional attributes to an element in React.

What is the state in react JS?

React components has a built-in state object. The state object is where you store property values that belongs to the component. When the state object changes, the component re-renders.


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>

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>

<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).


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