Search code examples
javascriptreactjsforms

Add a register value to new input field


I have a button which add a new text field on a react form. I want this new input text field to store data on a register. How can I set this property?

Usually when you create a text field you use the {...register("answer", { required: true })}.

Currently I have a function called addOption:

const addOption = (e) => {
         if (nOptions < 6) {
             setNOptions(() => nOptions + 1);
             let ctn = document.getElementById("options");
             let newInpit = document.createElement("input");
             ctn.appendChild(newInput);
         }
     };

This function adds an input field and works well, but have no idea of how to add the the register property to this field.


Solution

  • To add the register property to the dynamically created input field, you can modify your addOption function to use React's JSX syntax instead of directly manipulating the DOM. You can create a new component for the input field and use useForm to manage the form state and registration.

    EXAMPLE

    const [nOptions, setNOptions] = useState(0);
          const { register, handleSubmit } = useForm();
        
          const addOption = () => {
            if (nOptions < 6) {
              setNOptions(nOptions + 1);
            }
          };
        
          const onSubmit = (data) => {
            
            console.log(data);
          };
         
    return (
            <form onSubmit={handleSubmit(onSubmit)}>
              {/* Existing input fields */}
              {[...Array(nOptions)].map((_, index) => (
                <input key={index} {...register(`answer${index}`, { required: true })} />
              ))}
              
              {/* Button to add new input field */}
              {nOptions < 6 && <button type="button" onClick={addOption}>Add Option</button>}
              
              {/* Submit button */}
              <input type="submit" value="Submit" />
            </form>
          );