Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

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 ?

like image 992
Rajat kashyap Avatar asked Apr 14 '26 10:04

Rajat kashyap


2 Answers

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>
  );
}
like image 87
Alexey Kostyuhin Avatar answered Apr 16 '26 00:04

Alexey Kostyuhin


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

like image 32
Near Avatar answered Apr 15 '26 22:04

Near



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!