Home Backend Development Golang How to build a draggable list using Go and React

How to build a draggable list using Go and React

Jun 17, 2023 pm 01:12 PM
react go language Draggable list

In modern web applications, the drag-and-drop function has become one of the standard features because it can give users a better interactive experience. In this article, we will introduce how to use Go language and React to build draggable lists to make your web applications easier to use and more interesting.

Step 1: Build a back-end service

First, we need to build a back-end service to manage the list data. We will create a simple REST API using Go language. To simplify our code, we will use both the Gin framework and the GORM library.

First, we need to create a table called "items" to store our list items.

CREATE TABLE items (
    id INT NOT NULL AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,
    position INT NOT NULL,
    PRIMARY KEY (id)
);
Copy after login

Next, we create a Golang file and add the following code in it:

package main

import (
    "github.com/gin-gonic/gin"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"
)

type Item struct {
    ID       int    `gorm:"primary_key" json:"id"`
    Name     string `gorm:"not null" json:"name"`
    Position int    `gorm:"not null" json:"position"`
}

func main() {
    // 初始化Gin框架
    r := gin.Default()

    // 连接MySQL数据库
    db, err := gorm.Open("mysql", "{username}:{password}@/{database_name}?charset=utf8&parseTime=True&loc=Local")
    if err != nil {
        panic("无法连接到数据库")
    }
    defer db.Close()

    // 自动迁移schema
    db.AutoMigrate(&Item{})

    // 添加CORS中间件
    r.Use(corsMiddleware())

    // 定义API路由
    api := r.Group("/api")
    {
        api.GET("/items", listItems)
        api.PUT("/items/:id", updateItem)
    }

    // 启动服务
    r.Run(":8080")
}

// 列出所有项
func listItems(c *gin.Context) {
    db := c.MustGet("db").(*gorm.DB)

    var items []Item
    db.Find(&items)

    c.JSON(200, items)
}

// 更新单个项目
func updateItem(c *gin.Context) {
    db := c.MustGet("db").(*gorm.DB)

    // 从URL参数获得项目的ID
    id := c.Param("id")

    // 从请求体得到项目的其他项(名称和位置)
    var input Item
    if err := c.BindJSON(&input); err != nil {
        c.JSON(400, gin.H{"error": err.Error()})
        return
    }

    // 更新数据库
    var item Item
    if db.First(&item, id).RecordNotFound() {
        c.JSON(404, gin.H{"error": "项目未找到"})
        return
    }

    item.Name = input.Name
    item.Position = input.Position

    if err := db.Save(&item).Error; err != nil {
        c.JSON(400, gin.H{"error": "更新项目失败"})
        return
    }

    c.JSON(200, item)
}

// 添加CORS中间件
func corsMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
        c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS")
        c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type")
        c.Writer.Header().Set("Access-Control-Max-Age", "86400")
        if c.Request.Method == "OPTIONS" {
            c.AbortWithStatus(200)
            return
        }
        c.Next()
    }
}
Copy after login

In this code, we first create a table named "items" with to store list items. We then created a struct called "Item" and defined its fields in it. Next, we created a function called "listItems" that fetches all items from the database and returns them as JSON. We also created a function called "updateItem" that updates a single item.

We created a routing group named "api" in this Golang file and defined two routes: GET /items and PUT /items/:id. GET route is used to get all items and PUT route is used to update a single item.

We also added a middleware called "corsMiddleware" to handle CORS issues. CORS allows code in one domain to make requests to an API in another domain, which is very common when developing web applications.

Step 2: Build the React front end

Next, we need to create the React front end. We will use React and the React-DnD library to implement drag and drop functionality. We will also use the Axios library to get data from the backend server.

First, we need to create a folder called "ItemList" and save the following code to a file called "ItemList.jsx":

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';

export default function ItemList() {
    const [items, setItems] = useState([]);

    useEffect(() => {
        axios.get('http://localhost:8080/api/items').then((response) => {
            setItems(response.data);
        });
    }, []);

    function onDragEnd(result) {
        const { destination, source, draggableId } = result;
        if (!destination) {
            return;
        }
        if (
            destination.droppableId === source.droppableId &&
            destination.index === source.index
        ) {
            return;
        }

        const item = items.find((i) => i.id === parseInt(draggableId));
        const newItems = [...items];
        newItems.splice(source.index, 1);
        newItems.splice(destination.index, 0, item);

        axios
            .put(`http://localhost:8080/api/items/${draggableId}`, {
                name: item.name,
                position: destination.index,
            })
            .then(() => {
                setItems(newItems);
            });
    }

    return (
        <DragDropContext onDragEnd={onDragEnd}>
            <Droppable droppableId="itemList">
                {(provided) => (
                    <ul
                        {...provided.droppableProps}
                        ref={provided.innerRef}
                        className="item-list"
                    >
                        {items.map((item, index) => {
                            return (
                                <Draggable
                                    key={item.id}
                                    draggableId={item.id.toString()}
                                    index={index}
                                >
                                    {(provided) => (
                                        <li
                                            {...provided.draggableProps}
                                            {...provided.dragHandleProps}
                                            ref={provided.innerRef}
                                            className="item"
                                        >
                                            {item.name}
                                        </li>
                                    )}
                                </Draggable>
                            );
                        })}
                        {provided.placeholder}
                    </ul>
                )}
            </Droppable>
        </DragDropContext>
    );
}
Copy after login

In this React component , we first use useState and useEffect to get the data of the list items. Then, we created a function called "onDragEnd" to handle the drag event and update the data. We also created a draggable list using the React-DnD library. In this "ItemList" component, we render a

    element that contains all the list items and make them draggable using the component. We also use the component to wrap the entire list so that it can be dragged and dropped.

    Now, we need to use this component in our application. In our React application, we created a component called "App" and added an to its JSX. Next, we add the following code to a file called "index.js" to render our React application:

    import React from 'react';
    import ReactDOM from 'react-dom';
    import App from './App';
    
    ReactDOM.render(<App />, document.getElementById('root'));
    Copy after login

    Step 3: Run the application

    Now , we have completed the development of the application. We need to start the backend service and frontend React application to see them running. First, we need to double-open terminal windows, switch to our Go application directory in one window, and run the following command:

    go run main.go
    Copy after login

    Then, switch to our React application directory in the other terminal window, Run the following command:

    npm start
    Copy after login

    Now, we can visit http://localhost:3000/ in the browser and see our draggable list. Now you can play around and see if you can comfortably drag the list items and have them update accordingly in the backend service.

    Conclusion

    In this article, we used Go language and React to build a draggable list. Through Gin and React-DnD libraries, we implemented the function of dragging list items , and get data from the backend server through the Axios library. This sample project can be used as a reference in your daily work development.

    The above is the detailed content of How to build a draggable list using Go and React. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Vue.js vs. React: Project-Specific Considerations Vue.js vs. React: Project-Specific Considerations Apr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

React's Role in HTML: Enhancing User Experience React's Role in HTML: Enhancing User Experience Apr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

See all articles