Is there a way to disable all the input
s, button
s, select
s inside a react component on the basis of a state variable, or a prop of the component?
- My react component has multiple such buttons, and inputs.
- Some of them are rendered
disabled
on some boolean state variable, saybool1
as:<button disabled = {bool1}>Button 1</button>
- Some buttons are rendered
disabled
on some boolean state variable, saybool2
as:<button disabled = {bool2}>Button 2</button>
- Similarily, there are multiple elements that behave disabled on the basis of some state variable.
But what I want is, I have a state variable isCompDisabled
, which when true
, should disable all the inputs and buttons, etc. But, when it is false
, the button or input should then revert back to its state as decided by the other boolean variable. This behaviour can be implemented by adding a conditional for every element. In short, the behaviour should be like:
<button disabled = {boolX || isCompDisabled}>Button X</button>
The problem in my use case is, that it would be lengthy process going to each input or button, and add a disabled logic on it. Is there a short way, or an entire other way of fulfilling my use case?
2
Answers
Using Context:
DisableProvider
.Using Higher-Order Component (HOC):
The HOC method directly envelops your components and injects the global disable prop. The context method may offer more flexibility by permitting you to utilize the disabling logic in any component, deep within your component tree without having to overtly pass the prop down through many layers.
You can wrap all your inputs in a
<fieldset>
and use thedisabled
attribute there instead:Note that form elements inside the
<legend>
element won’t be disabled.See the fieldset documentation.