12

I am trying to implement a drag and drop functionality in lwc and I am getting the below code:

    <template for:each={leftTask} for:item="task">
        <div class="draggable" draggable="true" key={task.taskId} 
             ondragstart={handleDragStart(task.taskId)}>{task.name}
        </div>
    </template>

However, it seems that lwc doesn't allow passing parameters directly into handle functions. So the above code won't work. I am wondering is it possible to pass any parameter into js handler at all? Or do I have to make a separate child component in order to handle this?

2 Answers 2

36

You can read data directly from the target:

    <div data-id={task.taskId} class="draggable" draggable="true" key={task.taskId} 
      ondragstart={handleDragStart}>{task.name}</div>

    function handleDragStart(event) {
        var taskId = event.target.dataset.id;
        // ...
    }
2
  • @sfscfox do you know of a similar solution for the <button> tag? When I set data-id and try to access it via event.target.dataset.id, it does not exist. dataset doesn't actually exist.
    – BlondeSwan
    Commented May 30, 2019 at 21:29
  • 5
    @BlondeSwan try using event.currentTarget.dataset.id
    – Tolga E
    Commented Feb 29, 2020 at 22:23
3

If you are using a lightning button then -

<lightning-button data-id={rec.accId} label="my label" variant="border-filled" onclick={myFunc}></lightning-button>

in js file

myFunc(event){
        console.log(event.currentTarget.dataset.id);
}
1
  • I'm using a <span data-id="whatever" onclick...>. For that, event.target.dataset.id is undefined, but event.currentTarget.dataset.id works great. thanks. Commented Jul 13, 2023 at 16:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .