0

I have a form where i need to save the values as an array:

function App() {
  const {
    setValue,
    register,
    handleSubmit,
    watch,
    formState: { errors }
  } = useForm();
  const onSubmit = (data) => {
    console.log(data, "submit");
  }; // your form submit function which will invoke after successful validation
  const allValues = watch("example") || [];
  console.log(allValues);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      {[1, 2, 3].map((v, index) => {
        return (
          <input value={v} type="checkbox" {...register(`example[${index}]`)} />
        );
      })}

      <input
        onChange={(e) => {
          setValue("example", e.target.value);
        }}
      />

      <input type="submit" />
    </form>
  );
}

Here: setValue("example", e.target.value); i want to set my text input value inside the result, so when i add check some checkboxes like 1 and 2 and also add test value in text input, when i will save i need to get the next result [1,2,'test']. If there is not a value in text input i should't add anything in the array.
question: How to solve the issue? Now if i add test in array i get [t,e,s,t].
demo: https://codesandbox.io/s/react-hook-form-get-started-forked-q2xhj5?file=/src/index.js:129-840

1 Answer 1

0
import React, { useState } from "react";
import ReactDOM from "react-dom";
import { useForm } from "react-hook-form";

import "./styles.css";

function App() {
  const { setValue, getValues, register, handleSubmit } = useForm();
  const [inputValue, setInputValue] = useState("");
  const onSubmit = (data) => {
    if (inputValue) setValue("example", [...getValues().example, inputValue]);
    console.log(getValues().example);
  }; // your form submit function which will invoke after successful validation

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      {[1, 2, 3].map((v, index) => {
        return (
          <input value={v} type="checkbox" {...register(`example[${index}]`)} />
        );
      })}

      <input
        value={inputValue}
        onChange={(e) => {
          setInputValue(e.target.value);
        }}
      />

      <input type="submit" />
    </form>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

This is my solution. Some changes I made:

  1. I only add the input value to the "example" array onSubmit, not onChange.
  2. I made the input controlled, giving it a value property inputValue, and setting it in the onChange handler
  3. I made use of getValues function, to obtain the current elements of example array. Then I used setValue with the spread operator to add at the end of the array.

Feel free to ask me further questions!

--Ado

Edit 1: turns out I got it wrong, you don't want to add the input value to example every time on submit. Here is my new solution:

import React, { useState } from "react";
import ReactDOM from "react-dom";
import { useForm } from "react-hook-form";

import "./styles.css";

function App() {
  const {  getValues, register, handleSubmit } = useForm();
  const onSubmit = (data) => {
    console.log(getValues().example);
  }; // your form submit function which will invoke after successful validation
  const checkboxes = [1, 2, 3];
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      {checkboxes.map((v, index) => {
        return (
          <input value={v} type="checkbox" {...register(`example[${index}]`)} />
        );
      })}

      <input
      {...register(`example[${checkboxes.length}]`)}
      />

      <input type="submit" />
    </form>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Sign up to request clarification or add additional context in comments.

7 Comments

thank you, but the code does not work as expected, if i add text input value and sumbmit many times the result every time is different.
Ok so I made some changes, I thought you wanted to add the value every time.
I would also recommend that you add a key attribute to every checkbox, so you don't have the warning "every child must have a unique key". That's only a suggestion! For example: <input key={v} type="checkbox" {...register(example[${index}])} />. Also, I don't think you need the value property for the checkboxes, it's not that common to have a checkbox with a value of "1", "2" or "3", checkboxes are meant to have a value of true or false.
i have a question also here stackoverflow.com/questions/75172208/… , could you help please? It will help me a lot
please let me know when you have any results
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.