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?
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'.
Button component can be enabled/disabled by giving disabled property. To disable Button component, the disabled property can be set as true .
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With