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
Seems to wrong usage of UseState hook.
Your
addField
function is directly changingfields
, instead of usingsetFields
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: