1
votes

I am trying to create a sortable list with the react.js library "react-sortable-hoc" (https://github.com/clauderic/react-sortable-hoc).

In "SortableList" I map a function on each element of array which (should) create a "SortableElement" with the arguments key, index and value. This is how "SortableElement" is defined: https://github.com/clauderic/react-sortable-hoc/blob/master/src/SortableElement/index.js

SortableItem = SortableElement(({value,key}) =>
    <Row>
      <this.DragHandle/>
      <ControlLabel>Question</ControlLabel>
      <FormControl
        componentClass="textarea"
        placeholder="Enter question"
        onChange={()=> {
          console.log(key);       //why undefined??
          console.log(value);
        }
        }
      />
    </Row>);

SortableList = SortableContainer(({items}) => {
    return (
      <div>
        {items.map((value, index) =>
          <this.SortableItem key={`item-${index}`}
                             index={index}
                             value={value}/>
        )}
      </div>
    );
  });

Unfortunately, key and index are always undefined, and I just don't understand why. If you are interested in the full code, please visit https://github.com/rcffc/react-dnd-test/blob/master/src/SortableComponent.js

Any help is appreciated.

1

1 Answers

2
votes

If you look at the source for react-sortable-hoc, you'll see that when passing props in the render, index is omitted. Also, key isn't passed in props. If you change your destructuring to log props in SortableItem, you'll see an object containing just the value ('Question 1', 'Question 2', etc). If you need to access the index or key, pass them as different props.

e.g.

SortableItem = SortableElement(({value,yourIndex}) =>
    <Row>
      <this.DragHandle/>
      <ControlLabel>Question</ControlLabel>
      <FormControl
        componentClass="textarea"
        placeholder="Enter question"
        onChange={()=> {
          console.log(yourIndex);
          console.log(value);
        }
        }
      />
    </Row>
);

SortableList = SortableContainer(({items}) => {
    return (
      <div>
        {items.map((value, index) =>
          <this.SortableItem key={`item-${index}`}
                             index={index}
                             value={value}
                             yourIndex={index} />
        )}
      </div>
    );
});