The HTML element's
The state variable isReadOnly controls the disabled property of the input element. The below example is applicable for checkboxes and radio buttons as well.
import { useState } from "react"
export const App = () => {
const [isReadOnly, setIsReadOnly] = useState(false)
return(
<>
<div>
<input placeholder="Your name" disabled={isReadOnly}/>
</div>
<div>
<button onClick={() => setIsReadOnly(prev => !prev)}>
{isReadOnly ? "Enable Input" : "Disable Input"}
</button>
</div>
</>
)
}
export default App
import { useState } from "react"
export const App = () => {
const [isReadOnly, setIsReadOnly] = useState<boolean>(false)
return(
<>
<div>
<select disabled={isReadOnly}>
<option>Select</option>
<option>Windows</option>
<option>Mac</option>
<option>Linux</option>
<option>DOS</option>
</select>
</div>
<div>
<button onClick={() => setIsReadOnly(prev => !prev)}>
{isReadOnly ? "Enable select" : "Disable select"}
</button>
</div>
</>
)
}
export default App
The disabled property is applicable in the options as well. That will disable the relevant option instead of the entire select input.
<select>
<option>Select</option>
<option>Windows</option>
<option>Mac</option>
<option>Linux</option>
<option disabled={isReadOnly}>DOS</option>
</select>
import { useState } from "react"
export const App = () => {
const [isReadOnly, setIsReadOnly] = useState<boolean>(false)
return(
<>
<div>
<textarea placeholder="Your comments" disabled={isReadOnly}/>
</div>
<div>
<button onClick={() => setIsReadOnly(prev => !prev)}>
{isReadOnly ? "Enable textarea" : "Disable textarea"}
</button>
</div>
</>
)
}
export default App
import { useState } from "react"
export const App = () => {
const [isReadOnly, setIsReadOnly] = useState<boolean>(false)
return(
<>
<div>
<input list="os" disabled={isReadOnly}/>
<datalist id="os">
<option value="Mac"/>
<option value="Windows"/>
<option value="iOS"/>
<option value="Android"/>
<option value="Linux"/>
<option value="DOS"/>
</datalist>
</div>
<div>
<button onClick={() => setIsReadOnly(prev => !prev)}>
{isReadOnly ? "Enable datalist" : "Disable datalist"}
</button>
</div>
</>
)
}
export default App
Applying the disabled property at the option level will disable the particular option. However, if you disable an option, that option will disappear from the option list.
<datalist id="os">
<option value="Mac"/>
<option value="Windows"/>
<option value="iOS"/>
<option value="Android"/>
<option value="Linux"/>
<option value="DOS" disabled={isReadOnly}/>
</datalist>