Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

66
Visualizações
React Draggable property only being applied to final element in array

I am looking to add draggable list items to my DOM via JSX in react.

The expected output into the DOM should look like this:

<li draggable="true" style="border: 1px solid red;">Test Scenario 1</li>
<li draggable="true" style="border: 1px solid red;">Test Scenario 2</li>
<li draggable="true" style="border: 1px solid red;">Test Scenario 3</li>

But the actual output is:

<li style="border: 1px solid red;">Test Scenario 1</li>
<li style="border: 1px solid red;">Test Scenario 2</li>
<li draggable="true" style="border: 1px solid red;">Test Scenario 3</li>

Current code I have tried:

import React from 'react';
import { useDrag } from "react-dnd";

function LibraryItems(props) {

    const [{ isDragging }, dragRef] = useDrag(() => ({
        type: "li",
        collect: (monitor) => ({
            isDragging: monitor.isDragging(),
        }),
    }));

    
    // Declare and populate array of Library Scenarios
    const itemList = []
        
    props.items.map(item => {
        itemList.push(<li style={{border: 'red 1px solid'}} ref={dragRef}>{item.title}</li>);
    })

        
    return (
        <ul>
            {itemList}
        </ul>
    )
}

export default LibraryItems
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You basically need a dragRef for each li, I would do something like this:

  const itemList = [];
  const drags = {};
  
  props.items.forEach((item) => {
    const drag = useDrag(() => ({
      type: "li",
      collect: (monitor) => ({
        isDragging: monitor.isDragging()
      })
    }));

    const [{ isDragging }, dragRef] = drag;

    drags[item.title] = drag;

    itemList.push(
      <li style={{ border: "red 1px solid" }} ref={dragRef} key={item.title}>
        {item.title}
      </li>
    );
  });

If you want to check for example if a particular li is getting dragged you would access it via its title (they should be unique), for example for the li that has the title "li1":

console.log(drags["li1"][0].isDragging);

Working CodeSandbox.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda