简体   繁体   中英

Best way to control checkboxes during update | ReactJS

Suppose I have a form to post. It has checkboxes. (Bool type, receives 0 and 1 ). Creates the logic as follows.

 "is_has_n": values.is_has_n === true ? 1 : 0,

It returns a value of 1 and 0 if true (1) and false (0). It works without error while I was creating this post. If I want to edit this post I've some problems. So this checkbox was true before, and now it should now be false to me. So I can uncheck the checkbox when I am editing the post. I have the following form:

{
data.is_has_n === 1 ?
 (
    <Form.Check
        onChange={handleChange}
        name="is_has_n"
        defaultChecked={true}
        isInvalid={touched.is_has_n&& !!errors.is_has_n}
        type="checkbox"
        label="Label 
    />
) :
(
    <Form.Check
        onChange={handleChange}
        name="is_has_n"
        defaultChecked={false}
        isInvalid={touched.is_has_n&& !!errors.is_has_n}
        type="checkbox"
        label="Label
    />
 )

That is to me now if I want to set true checkbox to false. So I want to keep it unchecked during update psot. I mean. What can I do to check that how I control is checked or unchecked before submiting data? there should also be taken into checkboxes that there are several erroneous presses. I also thought of doing a method called isChecked, but I don't think it would be a solution. Because checkboxes may be pressed multiple times before save.

EDITED | FIXED I found solution for this: I did like that:

const [IsDangerous, setIsDangerous] = useState(data.dangerous_status === 1 ? true : false);

And my Handle change function

if (name === "dangerous_status") {
        console.log(isChecked);
        setFieldValue(name, isChecked);
        if (isChecked) {
            console.log("dangerous_status", true);
            setIsDangerous(true);
        } else {
            setIsDangerous(false);
            console.log("dangerous_status", false);
        }
    }

The question seems to be unclear, but I think you should use controlled components, thereby controlling input field values with the state. Refer https://reactjs.org/docs/forms.html .

<input type="checkbox" value={this.state.inputValue} onChange={this.handleChange} />

"value" binds the input to the state field inputValue which is changed by the handleChange. Control the value of inputValue to control wha to show in the input field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM