Rajat kashyap
Rajat kashyap

Reputation: 622

how to add input field dynamically when user click on button in react.js

I have two Question ->

First one is I want to add user input field dynamically when user click "+" button in react.js. And if user click more times then more number of field add to the form. How to do this in react.js?

Second one when user change its value I want to store their corresponding value of each input field into my component state variable. Now here how I add their value, what data structure I use array or object or something else ? and how ?

Upvotes: 10

Views: 41793

Answers (2)

Alexey Kostyuhin
Alexey Kostyuhin

Reputation: 404

function App() {
  const inputArr = [
    {
      type: "text",
      id: 1,
      value: ""
    }
  ];

  const [arr, setArr] = useState(inputArr);

  const addInput = () => {
    setArr(s => {
      return [
        ...s,
        {
          type: "text",
          value: ""
        }
      ];
    });
  };

  const handleChange = e => {
    e.preventDefault();

    const index = e.target.id;
    setArr(s => {
      const newArr = s.slice();
      newArr[index].value = e.target.value;

      return newArr;
    });
  };

  return (
    <div>
      <button onClick={addInput}>+</button>
      {arr.map((item, i) => {
        return (
          <input
            onChange={handleChange}
            value={item.value}
            id={i}
            type={item.type}
            size="40"
          />
        );
      })}
    </div>
  );
}

Upvotes: 19

Near
Near

Reputation: 447

I would set a counter and increase it with each click of a button. I would map the counter numbers into an array and loop over creating new input elements.

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [counter, setCounter] = useState(0);

  const handleClick = () => {
    setCounter(counter + 1);
    console.log(counter);
  };
  return (
    <div className="App">
      <button onClick={handleClick}>Hello</button>

      {Array.from(Array(counter)).map((c, index) => {
        return <input key={c} type="text"></input>;
      })}
    </div>
  );
}

https://codesandbox.io/s/elastic-wave-36ous?fontsize=14&hidenavigation=1&theme=dark

Upvotes: 15

Related Questions