I have a small implementation of drag and drop using react-dnd
. There are two columns, dragging from right side column to the left one activates the specific status item.
On drop, pushCard()
is called, which (as the name suggests), pushes the dragged item into the array of activated statuses i.e., status_data
.
But the problem is, status_data.push(itemToPush)
, pushes the new item at the end of the array. I wanted to push the item on top of the array i.e., index 0 of the array.
status_data.unshift(itemToPush)
works in this case, but unshift
only updates the array in the state
and on the backend, but it doesn't show the updated array
on the front-end. Rather it would just keep pushing the same element that was dragged first.
Simple description of problem in a GIF.
pushCard
:
pushCard(item) {
const { status_data } = this.state.template;
const itemToPush = {
title : item.title || 'CUSTOM',
type_id : item.type_id,
color : item.color || '#000',
type: item.type,
require_notes: item.require_notes || false,
require_estimate: item.require_estimate || false
};
status_data.unshift(itemToPush);
this.setState(Object.assign(this.state.template, { status_data }));
}
renderActiveStatuses
renderActiveStatuses() {
let renderedResult = '';
if (this.state.template.status_data.length < 0) {
renderedResult = (<p>No status active in this template.</p>);
} else {
renderedResult = this.state.template.status_data.map((status, i) => {
return (
<Status deleteStatus={this.deleteStatus} handleStatusUpdate={this.onStatusUpdate} index={i} id={status.id} moveCard={this.moveCard} statusData={status} key={status.id} />
);
});
}
return renderedResult;
}
renderActiveStatuses
is called in the render
function of the component.