Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

issue: Duplicated checkboxes create the same values in array #11864

Closed
1 task done
damian-balas opened this issue May 5, 2024 · 5 comments
Closed
1 task done

issue: Duplicated checkboxes create the same values in array #11864

damian-balas opened this issue May 5, 2024 · 5 comments

Comments

@damian-balas
Copy link

damian-balas commented May 5, 2024

Version Number

7.51.4

Codesandbox/Expo snack

https://codesandbox.io/p/sandbox/register-forked-cmmlpn

Steps to reproduce

  1. Select first checkbox
  2. Select first checkbox in red rectangle
  3. Submit
  4. Check console
  5. Output:
{
    "firstName": "",
    "lastName": "",
    "checkbox": [
        "A",
        "A"
    ],
    "radio": "",
    "message": ""
}

image

Expected behaviour

Checkboxes with the same registered name and value should "merge" and be in sync. If I select first checkbox, the first checkbox in red rectangle should be selected also.

before:

{
    "firstName": "",
    "lastName": "",
    "checkbox": [
        "A",
        "A"
    ],
    "radio": "",
    "message": ""
}

after:

{
    "firstName": "",
    "lastName": "",
    "checkbox": [
        "A",
    ],
    "radio": "",
    "message": ""
}

What's happening now (clicked only first checkbox):
image

What I want (clicked only first checkbox but the second one is in sync):
image

I want to duplicate all my inputs so I can show 50% of the form (4 inputs) on the initial view and 100% of the form (8 inputs) in a modal with a scrollbar.

What browsers are you seeing the problem on?

Firefox, Chrome, Safari, Edge

Relevant log output

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct
@bluebill1049
Copy link
Member

honestly not sure if we support your usage with multiple checkbox groups in different components.

@bluebill1049 bluebill1049 added the question Further information is requested label May 7, 2024
@damian-balas
Copy link
Author

@bluebill1049 Oh.. that's bad. I need to have 2 forms that are in sync. Is there a correct way to handle it using RHF?

Thanks for your fast feedback.
Really appreciate it :)

@erashu212
Copy link
Contributor

@damian-balas Do you mean if you update any value from form1 automatically those values should be appeared in modal form2?
If that is the case.

import { useEffect } from 'react';
import { useForm } from 'react-hook-form';

const useFormSync = (forms) => {
  useEffect(() => {
    const syncForms = (updatedForm, updatedValues) => {
      forms.forEach((form) => {
        if (form !== updatedForm) {
          Object.keys(updatedValues).forEach((name) => {
            form.setValue(name, updatedValues[name]);
          });
        }
      });
    };

    const unsubscribe = forms.map((form) =>
      form.watch((values) => syncForms(form, values))
    );

    return () => {
      unsubscribe.forEach((unsub) => unsub());
    };
  }, [forms]);
};

// Usage
function YourComponent() {
  const form1 = useForm();
  const form2 = useForm();

  useFormSync([form1, form2]);

  return (
    <>
      {/* Form 1 */}
      <form>
        <input name="field1" ref={form1.register} />
        <input name="field2" ref={form1.register} />
      </form>

      {/* Form 2 */}
      <form>
        <input name="field1" ref={form2.register} />
        <input name="field2" ref={form2.register} />
      </form>
    </>
  );
}

export default YourComponent;

@damian-balas
Copy link
Author

@erashu212 Thanks for your feedback!
I'll try it out soon and come back with some info :)

@erashu212
Copy link
Contributor

You can also try this way

import * as React from "react";
import { useForm } from "react-hook-form";
import Headers from "./Header";
import "./styles.css";

let renderCount = 0;

export default function App() {
  const { register, handleSubmit, setValue, watch } = useForm({
    defaultValues: {
      firstName: "",
      lastName: "",
      checkbox: [],
      radio: "",
      message: "",
    },
  });

  const checkboxValue = watch("checkbox", [])

  const handleCheckboxChange = React.useCallback((e) => {
    const { checked, value } = e.target;
    const newValue = checked ? [...checkboxValue, value] : checkboxValue.filter((v) => v !== value) 
    setValue("checkbox", newValue);
  }, [setValue, checkboxValue]);

  const onSubmit = (data) => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Headers renderCount={renderCount} />
      <input
        {...register("checkbox")}
        type="checkbox"
        value="A"
        onChange={handleCheckboxChange}
      />
      <input
        {...register("checkbox")}
        type="checkbox"
        value="B"
        onChange={handleCheckboxChange}
      />
      <input
        {...register("checkbox")}
        type="checkbox"
        value="C"
        onChange={handleCheckboxChange}
      />

      <div style={{ border: "1px solid red", padding: 12 }}>
        <h2>THIS IS A MODAL</h2>
        <p>Duplicated checkboxes with the same values!</p>
        <input
          {...register("checkbox")}
          type="checkbox"
          value="A"
          onChange={handleCheckboxChange}
        />
        <input
          {...register("checkbox")}
          type="checkbox"
          value="B"
          onChange={handleCheckboxChange}
        />
        <input
          {...register("checkbox")}
          type="checkbox"
          value="C"
          onChange={handleCheckboxChange}
        />
      </div>
      <input type="submit" />
    </form>
  );
}

@bluebill1049 bluebill1049 added design limitation work as designed and removed question Further information is requested labels May 19, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants