4

I'm trying out a sample using react-sortable-hoc. Sortables are failed to keep the state on sorting. Have a look at the GIF.

enter image description here

Below is my sample code..

import React, {Component} from 'react';
import {SortableContainer, SortableElement, arrayMove} from 'react-sortable-
hoc';
// Css
import './object_library.css'

const SortableItem = SortableElement(({value}) =>
<div className="Showcase_test_horizontalItem" >
    <div>{value}</div>
    <br />
    <TestSortable />
</div>
);

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

class TestSortable extends Component {
constructor(props) {
    super(props);
    this.state = {
        sum: 0
    }
    this.onAddChild = this.onAddChild.bind(this)
}
onAddChild () {
    let prevSum = this.state.sum + 1;
    this.setState({
        sum: prevSum
    });
}
render() {
    return (
        <div>
            <div> {this.state.sum} </div>
            <button className="my_plus_buttons" onClick={this.onAddChild}>+
            </button>
        </div>
    );
   }
 }

 class SortableComponent extends Component {
 state = {
    items: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6'],
 };
 onSortEnd = ({oldIndex, newIndex}) => {
    this.setState({
        items: arrayMove(this.state.items, oldIndex, newIndex),
    });
};
render() {
    return <SortableList items={this.state.items} onSortEnd={this.onSortEnd} 
    axis="x"/>;
  }
 }

 export default SortableComponent;

Not sure why this library is not maintaining states ?

Thanks

1 Answer 1

3

In your SortableList, you're setting a key based on the current index, which is a normal thing to do but it seems to be what causes the problem. Make the key match the value instead and it seems to work as expected.

I'd guess the key needs to move with the underlying component.

const SortableList = SortableContainer(({ items }) => {
  return (
    <div>
      {items.map((value, index) => (
        <SortableItem key={`item-${value}`} index={index} value={value} />
      ))}
    </div>
  );
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks it worked! I was missing the key inside SortableItem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.