-
I am using react dnd for drag and drop functionality and when I drag/drop an item, I want the Innerblocks order to update accordingly. I have attached a screenshot of having dragged tab 3 to position 1 but the inner blocks still show 1, 2, 3 when it should update to 3, 1, 2. I don't know if replaceInnerBlocks would be the way to go (not sure how to use that exactly) or what would be the best way to do it.
|
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
I think moveBlockToPosition might be helpful. Perhaps the implementation would be as follows (This has not been tested and may contain some errors). /**
* WordPress dependencies
*/
import { useDispatch, useSelect } from '@wordpress/data';
import { store as blockEditorStore } from '@wordpress/block-editor';
function Edit( { clientId } ) {
// Get child blocks
const { innerBlocks } = useSelect(
( select ) => select( blockEditorStore ).getBlocks( clientId ),
[ clientId ]
);
// Action to move a block to the specified index
const { moveBlockToPosition } = useDispatch( blockEditorStore );
// Run this in your timing.
function onSomeEvent( oldIndex, newIndex ) {
// Find the client id of the block you are trying to move.
const targetBlock = innerBlocks.find(
( block, index ) => index === oldIndex
);
if ( ! targetBlock ) {
return;
}
moveBlockToPosition(
targetBlock.clientId,
clientId,
clientId,
newIndex
);
}
} |
Beta Was this translation helpful? Give feedback.
-
Thank you for you feedback. I got it working like this before you posted your answer. However, if I refresh the page now and try to delete an item, it does not delete the inner block. I believe it is because the id's are changing on page refresh. Do you perhaps know how to handle that?
The delete handler
|
Beta Was this translation helpful? Give feedback.
-
I think client ids should not be kept as attributes because they change with each rendering. |
Beta Was this translation helpful? Give feedback.
I think client ids should not be kept as attributes because they change with each rendering.
It is better to control it by indexes only.