'How to implement Drag and Drop in Class based Component in react-dnd

I am new to react and trying to implement drag and drop with react-dnd. However I cant use hooks in class based components. I am getting an error due to the below portion of the code.

 const [{ isDragging }, drag] = useDrag({
           item: { type: ItemTypes.Student },
          collect: (monitor) => ({
            isDragging: !!monitor.isDragging(),
          }),
        });

How can I implement the same functionality while still using class based components? Below is the full code

class App extends Component {
  state = {
    values: [],
  };
const [{ isDragging }, drag] = useDrag({
      item: { type: ItemTypes.Student },
      collect: (monitor) => ({
        isDragging: !!monitor.isDragging(),
      }),
    });

  divStyle = {
    "margin-left": "20px",
  };

  componentDidMount() {
    axios.get("http://localhost:5000/api/student").then((response) => {
      this.setState({
        values: response.data,
      });
    });
  }

  render() {

    return (
      <div
        ref={drag}
        style={{
          opacity: isDragging ? 0.5 : 1,
          fontSize: 25,
          fontWeight: "bold",
          cursor: "move",
        }}
      >
        <Header as="h2">
          <Icon name="users" />
          <Header.Content>Reactivities</Header.Content>
        </Header>

        {this.state.values.map((student: any) => (
          <DndProvider backend={Backend}>
            <List key={student.id} relaxed>
              <List.Item>
                <Image
                  style={this.divStyle}
                  avatar
                  src="https://react.semantic-ui.com/images/avatar/small/daniel.jpg"
                />
                <List.Content>
                  <List.Header as="a">
                    {student.firstName} {student.lastName}
                  </List.Header>
                  <List.Description></List.Description>
                </List.Content>
              </List.Item>
            </List>
          </DndProvider>
          //  <List.Item key={value.id}>{value.name}</List.Item>
        ))}
      </div>
    );
  }
}

export default App;


Solution 1:[1]

You can't use hooks inside a class component, as explained here: https://reactjs.org/docs/hooks-faq.html#should-i-use-hooks-classes-or-a-mix-of-both

You can’t use Hooks inside a class component, but you can definitely mix classes and function components with Hooks in a single tree. Whether a component is a class or a function that uses Hooks is an implementation detail of that component. In the longer term, we expect Hooks to be the primary way people write React components.

As a consequence, if you want to use this library, you will need to refactor your component to be a function component.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ernesto