0

I'm having a hard time trying to convert my component. My main confusion is the useState. In my class based component it's easy to update my state with this.setState, but with hooks I'm quite confused about how thats achieved?

for example I can do this

onDrag = (event, item, currentDropZoneId, currentDropZoneItems) => {
event.preventDefault();
console.log("source", currentDropZoneId);
this.setState({
  dragSource: currentDropZoneId,
  draggedItem: item
});

};

and then use it my JSX

<Item
 draggable
 onDrag={event => this.onDrag(event, item, dropZone.id)}
 ey={item.id}
 />

How do I achieve the same functionality but with hooks? What is this.setState equalivent in react hooks?

invrt
  • 689
  • 6
  • 24

1 Answers1

1

You have 2 options to achieve updating state values with hooks:

  • the first option would be to declare 2 state variables (or more, depending on the needs of the component)
...
const [dragSource, setDragSource] = useState(...);
const [draggedItem, setDraggedItem] = useState(...);
...

const onDrag = (event, item, currentDropZoneId, currentDropZoneItems) => {
  event.preventDefault();
  console.log("source", currentDropZoneId);
  setDragSource(currentDropZoneId);
  setDraggedItem(item);
}

...

<Item
 draggable
 onDrag={event => onDrag(event, item, dropZone.id)}
 ey={item.id}
 />
  • the second option would be to create a single state variable for all the fields
...
const [state, setState] = useState({
  dragSource: ...,
  draggedItem: ...
});
...

const onDrag = (event, item, currentDropZoneId, currentDropZoneItems) => {
  event.preventDefault();
  console.log("source", currentDropZoneId);
  setState({
    dragSource: currentDropZoneId,
    draggedItem: item
  });
}

...

<Item
 draggable
 onDrag={event => onDrag(event, item, dropZone.id)}
 ey={item.id}
 />

Keep in mind that you no longer need to use 'this' keyword when invoking a function inside the current component, as the component is no longer a class, it became a function.

Nicu Timofte
  • 152
  • 1
  • 8