How to build a draggable list using Go and React

WBOY
Release: 2023-06-17 13:12:10
Original
1118 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!