Skip to content
Advertisement

React-Hook Form with useFieldArray: TextField value does not show up in the console. How can I fix it?

I wanted to enter the word Product but when I submit it, it does not show up in the console.

enter image description here

What shows up in the console:

As you can see here, the word Product does not appear in the console. Any idea on how I can solve this?

enter image description here

This is the codesandbox link: https://codesandbox.io/s/react-hook-form-usefieldarray-nested-arrays-forked-vjwbp?file=/src/index.js

this is the fieldArray.js where the input fields for products is

import React from "react";
import { useFieldArray } from "react-hook-form";
import NestedArray from "./nestedFieldArray";
import { TextField } from "@mui/material";

let renderCount = 0;

export default function Fields({ control, register, setValue, getValues }) {
  const { fields, append, remove, prepends } = useFieldArray({
    control,
    name: "test"
  });

  renderCount++;

  return (
    <>
      <ul>
        {fields.map((item, index) => {
          return (
            <li key={item.id}>
              {/* <select
                ref={register()}
                name={`test[${index}].name`}
                defaultValue={item.name}
              >
                <option value="">Select</option>
                <option value="10">ItemA</option>
                <option value="20">ItemB</option>
              </select> */}
              {/* {index + 1}  to show the qty */}
              <TextField
                name={`test[${index}].name`}
                refer={register()}
                defaultValue={item.name}
              />

              <button type="button" onClick={() => remove(index)}>
                Delete
              </button>
              <NestedArray nestIndex={index} {...{ control, register }} />
            </li>
          );
        })}
      </ul>

      <section>
        <button
          type="button"
          onClick={() => {
            append({ name: "append" });
          }}
        >
          Add product
        </button>
      </section>

      <span className="counter">Render Count: {renderCount}</span>
    </>
  );
}

Advertisement

Answer

you can change it try way:

fieldArray.js

<TextField
  name={`test[${index}].nestedArray[${index}].product`}
  inputRef={register({ required: true })}
  defaultValue={item.name}
/>;

enter image description here

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement