score:8

Accepted answer

You can use the useState hook to create a state variable that tracks whether the user has clicked the checkbox to disable the other input. The useState hook is a function that takes an initial value and returns a state variable and a function used to update the value of that state variable (which works pretty much the same as setState but only for a single state variable).

For example:

const [x, setX] = React.useState(1); // `x` is initially 1, but that will change on later renders

setX(prevX => prevX + 1); // increments `x` for the next render;

You'll also need to create an event handler function to respond to the clicking of this checkbox.

Here is a full example:

import React from "react";

const MyComponent = props => {
    const [disableInputIsChecked, setDisableInputIsChecked] = React.useState(false);
    const [inputValue, setInputValue] = React.useState("");

    function clearInput() {
        setInputValue("");
    }

    function handleInputChange(event) {
        setInputValue(event.target.value);
    }

    function handleCheckboxClick(event) {
        if (!disableInputIsChecked) { // this click was to check the box
            clearInput();
        }
        setDisableInputIsChecked(prevValue => !prevValue); // invert value
    }

    return (
        <form>
            <input type="checkbox" value={ disableInputIsChecked } onChange={ handleCheckboxClick }/>
            <input type="text" value={ inputValue } onChange={ handleInputChange } disabled={ disableInputIsChecked }/>
        </form>
    )
}

Here's a working example.

Probably you'll want to come up with better names for these values, but hopefully you get the point here.


Related Query

More Query from same tag