Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

61
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!