react-native-sortable-grid
react-native-sortable-grid copied to clipboard
Example of Dynamically Adding/Removing Children
Is there any example of how to dynamically add and remove children? If you add a child to the array do you have to re-render all of the children, or would it be best to use a state object?
First we setup our state data:
constructor() {
super()
this.state = {
favorites_data:
[{... Your JSON ...}]
};
...
Then added a function to add children:
addChildItem(itemData){
this.setState({
favorites_data: this.state.favorites_data.concat(itemData)
});
}
And in our render function we loop through the state:
renderChildren(){
return this.state.favorites_data.map( (item, index) =>
<View
...
Also if you are aiming for performance it is good to restrict the updates:
shouldComponentUpdate(nextProps, nextState){
if (this.state.favorites_data !== nextState.favorites_data) {
return true;
}
return false;
}
For removing (seems to only remove last item... looking into this)
removeChildItemAt(index){
var tmpArray = this.state.favorites_data.slice()
tmpArray.splice(index, 1);
this.setState({ favorites_data: tmpArray })
}
When you delete items by removing then from SortableGrid's children, make sure you're not assigning them their key-value from map-function index, because it causes the last item to disappear instead of the intended one. This happens because SortableGrid keeps copies of the children, and removes them based on missing keys when props update. If you assign the index of a map-function as a key for a child, SortableGrid only sees that the last key (last index) is missing and removes that.
@ollija Thank you, that is issue I was experiencing (removing only last item), however when I took off the key value when I map, only one single icon renders, instead of the 10 that should render.
Well, you need to assign them some key. Maybe increment a number each for each item and use that as a key?
Hrmm not sure I fully understand, Do you mean that the internal index and external should have different IDs? And thus you target this ID instead of the internal index?
I am still trying to figure out best way to implement the removal and insertion (Adding to end works fine) of items.
hello guys, i fixed it by generating random keys numbers,
key={Math.random() * 1000}
this delete the particular item not the last one.
@indivisable have you solved this problem? I'm facing the same issue...
so finally I got it working as well in updating adding children, key={Math.random() * index}. In my opinion I guess they need to add this on the documentation.