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
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);