Home > OS >  Adding a value from text input using spread operator in ReactJs
Adding a value from text input using spread operator in ReactJs

Time:01-21

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

CodePudding user response:

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

CodePudding user response:

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

import "./styles.css";

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
            key={v}
            name={"v"   v}
            value={v}
            type="checkbox"
            {...register(`example[${index}]`)}
          />
        );
      })}

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

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

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

  • Related