React Js Enable Disable Textbox on Checkbox Value
React Enable Disable textbox on checkbox value: To enable/disable a textbox in React on checkbox click, you can create a state variable to keep track of the checkbox's status. In the checkbox's onChange event, you can update the state variable with the current checked status. Then, in the textbox's props, you can conditionally set the disabled attribute to true or false based on the state variable's value using a ternary operator.
Thanks for your feedback!
Your contributions will help us to improve service.
How can I enable/disable a textbox in React based on a checkbox's click event?
This code is a React application that renders a container with a title, a checkbox, and an input field. The checkbox controls the "disabled" attribute of the input field, so when the checkbox is checked, the input field is disabled, and when the checkbox is unchecked, the input field is enabled.
Here is a breakdown of the code:
-
const { useState } = React;: This line imports theuseStatehooks from the React library. These hooks are used to manage state and side effects in React components. -
function App() { ... }: This defines theAppcomponent, which is a functional component in React. TheAppcomponent returns JSX, which is a syntax extension of JavaScript that allows you to write HTML-like code within your JavaScript code. -
const [disabled, setDisabled] = useState(false);: This line uses theuseStatehook to create a state variabledisabledwith an initial value offalse. ThesetDisabledfunction is used to update the value of thedisabledstate variable. -
<input type="checkbox" checked={disabled} onChange={(e) => setDisabled(e.target.checked)} />: This line renders a checkbox input element. Thecheckedprop is set to the value of thedisabledstate variable, which means that the checkbox will be checked whendisabledistrueand unchecked whendisabledisfalse. TheonChangeprop is a callback function that updates the value of thedisabledstate variable when the checkbox is checked or unchecked. -
<input type="text" disabled={!disabled} />: This line renders a text input element. Thedisabledprop is set to the opposite of thedisabledstate variable, which means that the input field will be disabled whendisabledistrueand enabled whendisabledisfalse.
Output of React Enable Disable textbox on checkbox click
