Home > Software design >  Why the the input length is 1?
Why the the input length is 1?

Time:04-04

The user has the possibility to generate input fields in order to enter a value, but what I want is the input length to be at 0.

const [inputList, setInputList] = useState([{ items: "" }]);


  const handleAddClick = () => {
    setInputList([...inputList, { items: "" }]);
  };

  console.log(inputList) // in the console it shows the length 1

  const handleItemChanged = (event, index) => {
    const value = event.target.value;
    const list = [...inputList];


    list[index].items = value;
    setInputList(list);
  };

  const handleRemoveClick = (index) => {
    const list = [...inputList];
    list.splice(index, 1);
    setInputList(list);
  };

So when the user goes to this component, it is shown an input field, and that's because the length as initial is 1.

How can I make it t he length to 0?

CodePudding user response:

Because you always have [{items:''}] at least in your array, which is array with one entry, therefore length 1.

CodePudding user response:

const [inputList, setInputList] = useState([]); // remove `{ items: "" }` from initial state

CodePudding user response:

At the time of declairation you already set a item. So if you want to the list length will be 0, at initial then do it as blank aray. like

const [inputList, setInputList] = useState([]);
  • Related