skip to Main Content

I have created a component to dynamically create a textbox based on button click

import React, { useState } from "react";
import ReactDOM from "react-dom";

const Input = () => {
  return <input placeholder="Your input here" />;
};

const Form = () => {
  const [inputList, setInputList] = useState([]);

  const onAddBtnClick = (event) => {
    setInputList(inputList.concat(<Input key={inputList.length} />));
  };

  return (
    <div>
      {inputList}
      <button onClick={onAddBtnClick}>Add input</button>
    </div>
  );
};

ReactDOM.render(<Form />, document.getElementById("form"));

So basically this loads a button on page load and create new textboxes everytime the "Add Input" button is clicked.

So sometimes, there can be scenarios like some values for textboxes are already available on pageload. In those cases, for example, if I have three values for TextBox available as a list ["Apple", "Mango", "Carrot"], then my page should have three TextBoxes created each with one of the values from the above list followed by the "Add Input" button

And If new textboxes are created, how to get the values of all the TextBox on button click.

Will this be possible to do in react.
Kindly guide me on how to approach this problem.

Any help is much appreciated.

Thanks,

3

Answers


  1. your input handler function should look like this,
      const onAddBtnClick = (event) => {
        setInputList([...inputList,<Input key={inputList.length} />]);
      };
    
    In this way you will get the previous input as well as your newly generated input element
    
    Login or Signup to reply.
  2. I think it is, you just need to modify your useState to initialize the state with these values. And then, capture the values of all the text boxes when a button is clicked, so you can maintain a reference to each input element and update the state accordingly.

    import React, { useState, useRef } from "react";
    import ReactDOM from "react-dom";
    
    const Input = ({ value, onChange }) => {
      return <input placeholder="Your input here" value={value} onChange={onChange} />;
    };
    
    const Form = () => {
      // Initial values for the text boxes
      const initialValues = ["Apple", "Mango", "Carrot"];
    
      // State to hold the current values of the text boxes
      const [inputList, setInputList] = useState(initialValues.map((val, index) => ({ value: val, id: index })));
    
      // Ref to hold references to the input elements
      const inputRefs = useRef([]);
    
      const onAddBtnClick = () => {
        // Add a new empty input field
        setInputList([...inputList, { value: "", id: inputList.length }]);
      };
    
      const onSubmit = () => {
        // Get the values of all the text boxes
        const values = inputList.map((input, index) => inputRefs.current[index].value);
        console.log(values); // Log the values to see them in the console
      };
    
      return (
        <div>
          {inputList.map((input, index) => (
            <Input
              key={input.id}
              value={input.value}
              ref={el => inputRefs.current[index] = el}
              onChange={e => setInputList(inputList.map((item, i) => i === index ? { ...item, value: e.target.value } : item))}
            />
          ))}
          <button onClick={onAddBtnClick}>Add input</button>
          <button onClick={onSubmit}>Submit</button>
        </div>
      );
    };
    
    ReactDOM.render(<Form />, document.getElementById("form"));
    
    
    Login or Signup to reply.
  3. This is another way to solve this.

    import React, { useState, useRef } from "react";
    import ReactDOM from "react-dom";
    
    const Input = (props) => {
      return <input {...props} placeholder="Your input here" />;
    };
    
    const Form = ({ data }) => {
      const [inputList, setInputList] = useState([]);
    
      useEffect(() => {
        setInputList(
          data.map((item, i) => (
            <Input
              id={`input${i}`}
              name={`input${i}`}
              key={i}
              defaultValue={item}
            />
          ))
        );
      }, [data]);
    
      const onAddBtnClick = (event) => {
        setInputList(
          inputList.concat(
            <Input
              id={`input${inputList.length}`}
              name={`input${inputList.length}`}
              key={inputList.length}
            />
          )
        );
      };
    
      const onSubmit = () => {
        var form = document.getElementById("form");
    
        var formData = {};
        for (var i = 0; i < form.elements.length; i++) {
          var element = form.elements[i];
          if (element.tagName === "INPUT" && element.type !== "button") {
            formData[element.name] = element.value;
          }
        }
    
        console.log(formData);
      };
    
      return (
        <div>
          {inputList}
          <button type="button" onClick={onAddBtnClick}>
            Add input
          </button>
          <button type="button" onClick={onSubmit}>
            Submit
          </button>
        </div>
      );
    };
    
    ReactDOM.render(<Form data={["Apple", "Mango", "Carrot"]} />, document.getElementById("form"));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search