Using Grid with SortableJS

1.9k Views Asked by At

I am using SortableJS for React and I am trying to implement horizontal Grid, so that the final result would look like this:

enter image description here

I managed to do that, however the sort function does not work at all. I think it has something to do with the tag attribute. When I try tag={Grid} I get following error:

Sortable: el must be an HTMLElement, not [object Object]

Any ideas how can I implement Grid to the tag attribute? Here is my code:

     <Grid container>
            <Sortable options={{ fallbackOnBody: true, group: "items", handle: reorderHandle }} tag={Grid} onChange={handleChange}>
                {items.map((item, index) =>
                    <Paper key={index} data-id={index} className={classes.item} elevation={0}>
                        <ButtonHelper {...getHandleClass(editable)} key={index} icon={
                            <Badge badgeContent={index + 1} color="default">
                                {editable && <ReorderIcon />}
                            </Badge>}
                        />
                        <Grid item xs={4} key={index}>
                            <div className={classes.gridItem}>
                                <GalleryInput className={classes.image} style={{ width: '300px' }} label="image" source={`${source}[${index}].image`} />
                                <br></br>
                                <TextInput label="desc" source={`${source}[${index}].desc`} />
                                {editable && <ButtonHelper icon={<RemoveIcon />} onClick={handleRemove(index)} className={classes.left} />}
                            </div>
                        </Grid>
                    </Paper>
                )}
            </Sortable>
        </Grid>

Thank you for any help.

2

There are 2 best solutions below

0
On

Try putting the Paper component inside a div

1
On

Since you are using a custom component, the tag prop accepts it as a forwarRef component only.

So you need to update in that way.

Sample Snippet

// This is just like a normal component, but now has a ref.
const CustomComponent = forwardRef<HTMLDivElement, any>((props, ref) => {
  return <div ref={ref}>{props.children}</div>;
});

export const BasicFunction: FC = props => {
  const [state, setState] = useState([
    { id: 1, name: "shrek" },
    { id: 2, name: "fiona" }
  ]);

  return (
    <ReactSortable tag={CustomComponent} list={state} setList={setState}>
      {state.map(item => (
        <div key={item.id}>{item.name}</div>
      ))}
    </ReactSortable>
  );
};