Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to disabled DIV onClick in React

I have a component with a div that accepts onClick and aria-disabled properties. Both of them come in as props, with disabled being an optional one. In my render method I do the following:

<div onClick={!this.props.Disabled ? this.props.Click : undefined} 
     aria-disabled={this.props.Disabled>My Div</div>

I use CSS to visualize the disabled state (opacity: 0.5, pointer-event: none blah blah). But I wonder if there's a better way to handle the actual onClick. Since it's a mandatory prop... so even when the item is disabled you still need to pass in an onClick to meet the condition. Is there a better way to go about this?

like image 309
blankface Avatar asked Jul 27 '18 00:07

blankface


People also ask

How do you disable onClick event of div in react?

The above code makes the contents of the div disabled, You can make the div disabled by adding the disabled attribute. Upon clicking the button you can change the state variable disabled as 'true'.

Can we disable a div in react?

Button component can be enabled/disabled by giving disabled property. To disable Button component, the disabled property can be set as true .

How do you make a div readOnly in react JS?

To control the mode of input element define readOnly attribute with it and control it's value by state variable, Whenever you update the state value react will re-render the component and it will change the mode on the basis of state value.

Can a div have an onClick 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.


2 Answers

Set pointer-events: none for the div[disabled] in CSS,

test.scss

div[disabled]
{
  pointer-events: none;
  opacity: 0.7;
}

The above code makes the contents of the div disabled, You can make the div disabled by adding the disabled attribute.

Test.js

<div disabled={this.state.disabled}>
  /* Contents */
</div>

Upon clicking the button you can change the state variable disabled as 'true'.

handleClick = () =>{
    this.setState({
      disabled: true,
    });
  }

Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events

like image 173
Pramod H G Avatar answered Sep 17 '22 08:09

Pramod H G


I think you're intuition is right -- not ideal to be adding and removing event handlers all the time based on changing props. How about simply wrapping the function and returning as needed? As in the following E.g.

<div onClick={(e) => !this.props.Disabled && this.props.Click(e)}
  aria-disabled={this.props.Disabled}>
    My Div
</div>

Where the guard operator && is shorthand for if logic.

like image 22
jpsimons Avatar answered Sep 18 '22 08:09

jpsimons