javascriptreactjsundefinedreact-sortable-hoc

TypeError: Cannot set property 'name' of undefined on "onChange" event using React-Sortable-hoc


I'm getting "TypeError: Cannot set property 'name' and 'quantity' of undefined" when I try to input data on any of the input form fields.

This started when I applied the React-Sortable HOC library to be able to drag and drop each list item to sort.

See complete code: https://codesandbox.io/s/sortable-list-wfpbk?file=/src/AddItem.js

 
 const [inputList, setInputList] = useState([{ name: "", quantity: "" }]);
 
 // handle input change
  const handleInputChange = (e, index) => {
    const { name, value } = e.target;
    const list = [...inputList];
    list[index][name] = value;
    setInputList(list);
  };
  
   const shoppingList = inputList.map((element, i) => {
      <div className="form" key={i}>
        
        <input
          className="form-field item-form-field"
          name="name"
          placeholder="Name"
          value={element.name}
        />
        <input
          className="form-field item-form-field"
          type="number"
          name="quantity"
          placeholder="Amount"
          // className="ml10"
          min="1"
          max="12"
          value={element.quantity}
        ></input>
        {inputList.length !== 1 && (
          <button className="remove-btn remove-btn-3 remove-btn-sep"> Remove</button>
        )}
      </div>
  })

  const SortableItem = SortableElement(({value, index}) => (
    
    <div className="form">
      <DragHandle />
    <input
      className="form-field item-form-field"
      name="name"
      placeholder="Name"
      value={value.name}
      onChange={(e) => handleInputChange(e, index)}
      
    />
    <input
      className="form-field item-form-field"
      type="number"
      name="quantity"
      placeholder="Amount"
      min="1"
      max="12"
      value={value.quantity}
      onChange={(e) => handleInputChange(e, index)}
    ></input>
    {inputList.length !== 1 && (
      <button className="remove-btn remove-btn-3 remove-btn-sep"
        onClick={() => handleRemoveClick(index)}
      >
      Remove
      </button>
    )}
  </div>


Solution

  • Hey, check out the below codesandbox link, you're issue is fixed.

    Link: https://codesandbox.io/s/sortable-list-forked-ne6hp?file=/src/AddItem.js

    The issue was with sortableElement, it does not accept index as a prop. It looks like the index is explicitly omitted in SortableElement.

    So, I have passed down another prop with a name like indexTemp={index}.