admin管理员组

文章数量:1312836

I am creating an app where different sentences can be ranked using drag and drop feature using react. My problem is whenever an item of smaller size is dragged over item of larger size, the smaller item streches. When an item with larger size is dragged over item with smaller size , the larger item shrinks.

I need to preserve the size of the dragged item when it is dragged.

Any idea how it can be done?

my code is as follow:

App.jsx

import React, { useState, useEffect } from 'react';
import { DndContext, closestCenter,useTransform } from '@dnd-kit/core';
import {
  arrayMove,
  SortableContext,
  verticalListSortingStrategy

} from '@dnd-kit/sortable';
import 'bootstrap/dist/css/bootstrap.min.css';
import { SortableItem } from './SortableItem.jsx';
import './App.css';

function App() {
  const [ranking, setRanking] = useState([
    "I dont understand why people dont accept that no matter what,Boys will be boys and men will be men",
    "She is such a drama queen.",
    "Don't be a sissy.",
    "Man is a better driver than women.",
    "God is a man."
  ]);

  function handleDragEnd(event) {
    console.log('Drag');
    const { active, over } = event;
    console.log('Active:' + active.id);
    console.log('Over :' + over.id);

    
    if (active.id !== over.id) {
      setRanking((items) => {
        const activeIndex = items.indexOf(active.id);
        const overIndex = items.indexOf(over.id);
        console.log(arrayMove(items, activeIndex, overIndex));
        return arrayMove(items, activeIndex, overIndex);
      });
    }
  }


  return (
    <div>
      <DndContext collisionDetection={closestCenter} onDragEnd={handleDragEnd} >
        <h3 style={{ color: 'black', fontWeight: 'bold' }} align="center">
          Rank the following sentences from most to least sexist.
        </h3>
        <div className="frame">
          <SortableContext items={ranking} strategy={verticalListSortingStrategy}>
            {ranking.map((rank) => (
              <SortableItem key={rank} id={rank} className="sortable-item" />
            ))}
          </SortableContext>
          <div className="button" style={{ display: 'flex', justifyContent: 'center' }}>
            <button
              className="btn submit-button"
              align="center"
              onClick={(e) => {
                e.preventDefault();
                console.log(ranking);
              }}
            >
              Submit
            </button>
          </div>
        </div>
      </DndContext>
    </div>
  );
}

export default App;

SortableItem.jsx

import React from "react";
import Card from 'react-bootstrap/Card';

import { useSortable } from "@dnd-kit/sortable";
import {CSS} from "@dnd-kit/utilities";

export function SortableItem(props){
    //props.id
const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition
} = useSortable({id: props.id});

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    marginBottom: "1rem",
  };

  return (
    <div
      ref={setNodeRef}
      style={style}
      {...attributes}
      {...listeners}
      className="hover-card"
    >
      <Card body>{props.id}</Card>
    </div>
  );
}

I tried using useTransform, useref, giving dimension to the card, also tried using responsive css but it didnt work as expected.

PS, i am very new to reactjs

Thank you

Sitashma

I am creating an app where different sentences can be ranked using drag and drop feature using react. My problem is whenever an item of smaller size is dragged over item of larger size, the smaller item streches. When an item with larger size is dragged over item with smaller size , the larger item shrinks.

I need to preserve the size of the dragged item when it is dragged.

Any idea how it can be done?

my code is as follow:

App.jsx

import React, { useState, useEffect } from 'react';
import { DndContext, closestCenter,useTransform } from '@dnd-kit/core';
import {
  arrayMove,
  SortableContext,
  verticalListSortingStrategy

} from '@dnd-kit/sortable';
import 'bootstrap/dist/css/bootstrap.min.css';
import { SortableItem } from './SortableItem.jsx';
import './App.css';

function App() {
  const [ranking, setRanking] = useState([
    "I dont understand why people dont accept that no matter what,Boys will be boys and men will be men",
    "She is such a drama queen.",
    "Don't be a sissy.",
    "Man is a better driver than women.",
    "God is a man."
  ]);

  function handleDragEnd(event) {
    console.log('Drag');
    const { active, over } = event;
    console.log('Active:' + active.id);
    console.log('Over :' + over.id);

    
    if (active.id !== over.id) {
      setRanking((items) => {
        const activeIndex = items.indexOf(active.id);
        const overIndex = items.indexOf(over.id);
        console.log(arrayMove(items, activeIndex, overIndex));
        return arrayMove(items, activeIndex, overIndex);
      });
    }
  }


  return (
    <div>
      <DndContext collisionDetection={closestCenter} onDragEnd={handleDragEnd} >
        <h3 style={{ color: 'black', fontWeight: 'bold' }} align="center">
          Rank the following sentences from most to least sexist.
        </h3>
        <div className="frame">
          <SortableContext items={ranking} strategy={verticalListSortingStrategy}>
            {ranking.map((rank) => (
              <SortableItem key={rank} id={rank} className="sortable-item" />
            ))}
          </SortableContext>
          <div className="button" style={{ display: 'flex', justifyContent: 'center' }}>
            <button
              className="btn submit-button"
              align="center"
              onClick={(e) => {
                e.preventDefault();
                console.log(ranking);
              }}
            >
              Submit
            </button>
          </div>
        </div>
      </DndContext>
    </div>
  );
}

export default App;

SortableItem.jsx

import React from "react";
import Card from 'react-bootstrap/Card';

import { useSortable } from "@dnd-kit/sortable";
import {CSS} from "@dnd-kit/utilities";

export function SortableItem(props){
    //props.id
const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition
} = useSortable({id: props.id});

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    marginBottom: "1rem",
  };

  return (
    <div
      ref={setNodeRef}
      style={style}
      {...attributes}
      {...listeners}
      className="hover-card"
    >
      <Card body>{props.id}</Card>
    </div>
  );
}

I tried using useTransform, useref, giving dimension to the card, also tried using responsive css but it didnt work as expected.

PS, i am very new to reactjs

Thank you

Sitashma

Share Improve this question edited Aug 26, 2023 at 20:17 Werthis 1,1176 silver badges22 bronze badges asked Jul 10, 2023 at 10:09 Sitashma RajbhandariSitashma Rajbhandari 411 silver badge3 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

In styles as a value of transform you should use CSS.Translate.toString(transform) not CSS.Transform.toString(transform).

  const style = {
    transform: CSS.Translate.toString(transform),
    transition,
    marginBottom: "1rem",
  };

Here you can find it: https://github./clauderic/dnd-kit/issues/117

This discussion on GitHub fixed it for me:

The items are stretched because you're using CSS.Transform.toString(), use CSS.Translate.toString() if you don't want to have the scale transformation applied.

You can customize the transform and transition properties of the sortable items using the useTransform hook. This hook allows you to apply custom transformations to draggable elements based on their position or state. For example, you can modify your SortableItem.jsx file like this:

import React from "react";
import Card from "react-bootstrap/Card";

import { useSortable, useTransform } from "@dnd-kit/sortable";

export function SortableItem(props) {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ id: props.id });

  const style = useTransform(
    transform,
    (transform) => {
      if (isDragging) {
        return {
          ...transform,
          width: "auto",
          height: "auto",
          margin: "1rem",
          boxShadow: "0 0 10px rgba(0,0,0,0.2)",
        };
      }
      return {
        ...transform,
        transition,
      };
    },
    [isDragging]
  );

  return (
    <div
      ref={setNodeRef}
      style={style}
      {...attributes}
      {...listeners}
      className="hover-card"
    >
      <Card body>{props.id}</Card>
    </div>
  );
}

本文标签: javascriptPreserve the size of dragged item while dragging it over another item in reactStack Overflow