Home > Back-end >  Why the input is undefined?
Why the input is undefined?

Time:04-02

What I'm trying to do is to add and remove input fields.

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

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

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

    console.log('list', list)
    console.log('value', value)
    console.log('items', items)
  };

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


return (
    <div>
      <div>
        {inputList.map((o, i) => {
          return (
            <tr key={"item-"   i}>
              <td>
                <div>
                  <input
                    type="text"
                    value={o.items}
                    autoComplete="off"
                    onChange={event => handleItemChanged(event, i)}
                  />
                </div>
              </td>
           </tr>
          )
         )}
      </div>
    </div>

The problem is that when I type a word inside the input, it won't write anything. In my console, it shows me the items is undefinded.

How can I fix it?

CodePudding user response:

As i can see you are trying to store values inside multiple inputbox and want to render it

what are you doing wrong?

1.trying to get items from event.target

2 assigning value to undefined member like list[index][items] = value;

So,what to do to make it work?

i assume items is just a text that you get from inputbox,if its so then,

you can correct the input handler like this

const handleItemChanged = (event, index) => {
//old code,there is no node named items in event.target
//const { items, value } = event.target;
const value=event.target.value;
const list = [...inputList];
//old code,since items is undefined you cant access it this way
//list[index][items] = value;
//the correct way to do it
list[index].items=value;
setInputList(list);

console.log('list', list)
console.log('value', value)
console.log('items', list[index].items)

};
  • Related