skip to Main Content

I’m trying to add field on Button Click but by default field is not showing and not adding on button click

i’ve tried my best but i don’t know what is the problem i added functions and use Math for generate unique id console.log is is working perfectly nut fields are not showing

"use client";
import React, { useState } from "react";
import { Button } from "../ui/button";

const DynamicForm = () => {
  const [fields, setFields] = useState([]);

  const addField = (event) => {
    event.preventDefault();
    const newFieldId = Math.random().toString(36).substring(2, 15);
    fields.push(...fields, { label: "", type: "text", id: newFieldId });
    console.log(fields);
  };

  const handleFieldChange = (index, event) => {
    const updatedFields = [...fields];
    updatedFields[index].label = event.target.value;
    setFields(updatedFields);
  };

  const handleTypeChange = (index, event) => {
    const updatedFields = [...fields];
    updatedFields[index].type = event.target.value;
    setFields(updatedFields);
  };

  return (
    <>
      <form>
        <h2>Dynamic Form</h2>
        {fields.map((field, index) => (
          <div key={field.id}>
            <label htmlFor={field.id}>Label: </label>
            <input
              id={field.id}
              name={field.id}
              value={field.label}
              onChange={(e) => handleFieldChange(index, e)}
            />
            <select
              value={field.type}
              onChange={(e) => handleTypeChange(index, e)}
            >
              <option value="text">Text</option>
              <option value="email">Email</option>
            </select>
            <Button onClick={() => setFields(fields.slice(0, index))}>
              Remove
            </Button>
          </div>
        ))}
        <div className="gap-3">
          <Button onClick={addField}>Add Field</Button>
        </div>
      </form>
    </>
  );
};

export default DynamicForm;

2

Answers


  1. Seems to wrong usage of UseState hook.

    const addField = (event) => {
        event.preventDefault();
        const newFieldId = Math.random().toString(36).substring(2, 15);
        setFields([...fields,{ label: "", type: "text", id: newFieldId }])
        // fields.push(...fields, { label: "", type: "text", id: newFieldId });
        // logging Fields here will not work because setFields is async in nature.
        // console.log(fields);
      };
    
    Login or Signup to reply.
  2. Your addField function is directly changing fields, instead of using setFields function. Using the function tells react that a state is changed and the component should be updated. Here’s what your function should look like:

      const addField = (event) => {
        event.preventDefault();
        const newFieldId = Math.random().toString(36).substring(2, 15);
        // using setFields function instead of directly changing the fields.
        setFields(prevData => [...prevData, { label: "", type: "text", id: newFieldId }]); 
      };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search