2

Hello guys I have created a material UI form with the help of react hook form and useFieldArray hook.

 <Box component="form" onSubmit={handleSubmit(submit)}>
      <Grid container spacing={2}>
        <Grid item xs={12} sm={12} md={12} lg={12}>
          <TextField
            label="Evnet Name"
            fullWidth
            {...register("eventName")}
            name="eventName"
          />
        </Grid>

        <Grid item xs={12} sm={12} md={6} lg={6} alignSelf="center">
          <TextField
            label="Evnet Venue Name"
            fullWidth
            {...register("eventVenue")}
            name="eventVenue"
          />
        </Grid>
         <Box sx={{ width: "100%" }}>
          <DialogTitle
            sx={{ fontWeight: "bold", textTransform: "uppercase" }}
          >
            Ticket Category
          </DialogTitle>
        </Box>
        <Grid item xs={12} sm={12} md={5} lg={4}>
          <TextField
            label="Category"
            fullWidth
            {...register("ticketCatName")}
            name="ticketCatName"
          />
        </Grid>

        <Grid item xs={12} sm={12} md={3} lg={3}>
          <TextField
            type="number"
            label="Price"
            fullWidth
            {...register("ticketCatPrice")}
            name="ticketCatPrice"
          />
        </Grid>

        <Grid item xs={12} sm={12} md={3} lg={3}>
          <TextField
            type="number"
            label="Total"
            fullWidth
            {...register("ticketCatTotal")}
            name="ticketCatTotal"
          />
        </Grid>
This Values I am getting when I submit the form. 
</Box>

I have create a dynamic form component which I am showing with map.

{fields.map((item, index) => {
              return (
                <MoreFields
                  register={register}
                  key={item.id}
                  remove={remove}
                  index={index}
                  item={item}
                  control={control}
                />
              );
            })}

The value on fields array is not showing data when I submit the form, other fields which not in fields array is working fine.

This is the code of component.

import { Box, Grid, IconButton, SvgIcon, TextField } from "@mui/material";
import React from "react";
import DeleteIcon from '@mui/icons-material/Delete';
import { Fragment } from "react";

const MoreFields = ({ register, remove, index, item }) => {
  return (
    <Fragment key={item.id}>
      <Grid item xs={12} sm={12} md={5} lg={4}>
        <TextField
          label="Category"
          fullWidth
          {...register(`ticketCategory.${index}.ticketCatName`)}
          name={`ticketCategory${index}.ticketCatName`}
          defaultValue={item.ticketCatName}
        />
      </Grid>

      <Grid item xs={12} sm={12} md={3} lg={3}>
        <TextField
          type="number"
          label="Price"
          fullWidth
          {...register(`ticketCategory.${index}.ticketCatPrice`)}
          name={`ticketCategory${index}.ticketCatPrice`}
          defaultValue={item.ticketCatPrice}
        />
      </Grid>

      <Grid item xs={12} sm={12} md={3} lg={3}>
        <TextField
          type="number"
          label="Total"
          fullWidth
          {...register(`ticketCategory.${index}.ticketCatTotal`)}
          name={`ticketCategory${index}.ticketCatTotal`}
          defaultValue={item.ticketCatTotal}
         
        />
      </Grid>

      <Grid item xs={4} sm={4} md={2} lg={2} alignSelf="center">
        <SvgIcon color='error' onClick={()=>remove(index)} sx={{cursor:'pointer'}}>
          <DeleteIcon size="medium" />
        </SvgIcon>
      </Grid>
      </Fragment>
  );
};

export default MoreFields;

I can get form when I append and even can delete the fields also but when submit value is not coming. don't know why please help me.

hooks and function I am using for this.

const { register, handleSubmit, control } = useForm();
  const { fields, append, prepend, remove, swap, move, insert } = useFieldArray(
    {
      control,
      name: "ticketCategory",
    }
  );
  const addFields = () => {
    append({ ticketCatName: "", ticketCatPrice: "", ticketCatTotal: "" });
  };

  const submit = (data) => {
    console.log(data);
  };

1 Answer 1

2

You should use the same name for both register and name prop like this:

<TextField
  label="Category"
  fullWidth
  {...register(`ticketCategory.${index}.ticketCatName`)}
  name={`ticketCategory.${index}.ticketCatName`}
  defaultValue={item.ticketCatName}
/>;

React Hook Form needs you to put the index in the array name because it uses the dot notation to access nested fields. For example, suppose you have an array of objects like this:

{
  "ticketCategory": [
    {
      "ticketCatName": "A",
      "ticketCatPrice": 10,
      "ticketCatTotal": 100
    },
    {
      "ticketCatName": "B",
      "ticketCatPrice": 20,
      "ticketCatTotal": 200
    }
  ]
}

Then each input name should match the path of the field in the form data. For example, the first ticket category name input should have the name ticketCategory.0.ticketCatName, and the second ticket category price input should have the name ticketCategory.1.ticketCatPrice. This way, React Hook Form can control the input value to the form data.

2
  • just fixed sir, I just put the index in array and its working now. don't know why. ``` name={ticketCategory[${index}].ticketCatPrice} ```
    – nehat khan
    Commented Jul 13, 2023 at 17:50
  • 1
    I updated my answer with the reason. - @nehatkhan
    – Pluto
    Commented Jul 13, 2023 at 18:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.