Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why the input is undefined?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)

};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading