Home Web Front-end Front-end Q&A Can react be used with g6?

Can react be used with g6?

Dec 20, 2022 pm 05:08 PM
react

react can use g6. How to use it: 1. Introduce AntV G6 into the project through the "npm install --save @antv/g6" command; 2. Use "yarn install" to reload the dependencies; 3. Just introduce G6 into the js file that needs to use G6.

Can react be used with g6?

#The operating environment of this tutorial: Windows 10 system, react18 version, Dell G3 computer.

Can react use g6?

can be used.

Using AntV G6 in React

AntV G6: G6 is a simple, easy-to-use, and complete graph visualization engine. It provides A series of elegantly designed and easy-to-use graph visualization solutions. It can help developers build their own graph visualization, graph analysis, or graph editor applications. Official website

Introduction of AntV G6

Use npm to introduce the package in the project

npm install --save @antv/g6
Copy after login

Reload dependencies

yarn install
Copy after login

In the js file that needs to use G6 After introducing G6

import G6 from '@antv/g6';
Copy after login

, the preparation work is over. Let’s start using G6 to draw the required relationship diagram, taking the force-directed diagram as an example to describe one-to-many and one-to-one relationships.

Use of AntV G6

Create a container: Create a container in HTML to accommodate the diagram drawn by G6, usually a div tag. When G6 draws, it will append the canvas tag under the container, and then draw the image in it.

ref: In React, you can get the real DOM element through ref.current. Forwarding Refs (Official Document)

<div ref={ref} id="test"/>
Copy after login

Creating a relationship diagram: When creating a relationship diagram (instantiation), at least the container, width and height need to be set for the diagram. For the rest, please refer to the API corresponding to the legend and the official API document to configure as needed.

   graph = new G6.Graph({
     container: ref.current,
     width: width < 1000 ? 387 : width,
     height: width < 1000 ? 220 : 550,
     layout: {
       type: &#39;force&#39;,
       preventOverlap: true,
       linkDistance: (d) => {
         if (d.source.id === &#39;node0&#39;) {
           return 10;
         }
         return 80;
       },
       nodeStrength: (d) => {
         if (d.isLeaf) {
           return 200;
         }
         return -500;
       },
       edgeStrength: (d) => {
         if (d.source.edgeStrength) {
           return 0.1;
         }
         return 0.8;
       },
     },
     defaultNode: {
       color: &#39;#5B8FF9&#39;,
     },
     edgeStateStyles: {
       highlight: {
         stroke: &#39;#5B8FF9&#39; // 这个颜色可以根据个人喜好进行修改
       }
     },
     modes: {
       default: [&#39;drag-canvas&#39;, &#39;zoom-canvas&#39;],
     },
   });
Copy after login

Data processing and preparation: Process the data according to the data format of the required chart.

Configure the data source and render:

graph.data(data); // 读取 Step 2 中的数据源到图上
graph.render(); // 渲染图
Copy after login

After explaining the basic use of AntV G6, you need to note that in React, G6 is different from AntV L7 and AntV G2, BizCharts, AntV G6 is You need to access nodes during use. When using its graph as a component, if you ignore this, problems will occur. Using G6 in React (official website document)

AntV G6 Note in React

  • Return the Demo that renders G6 graphics as an anonymous function, and at the same time The function return should be the container created above, which is used as a component when calling Demo in other js files, and the parameters passed in are the formal parameters of the anonymous function.

  • The instance generated in the second step above: "Create the relationship diagram" should be defined in the side effect useEffect.

  • Due to obtaining data in CompotentDidMount, when rendering the Demo, there may be data that does not receive a response before rendering the Demo, resulting in an error. The solution is as follows:

{deviceData.length ? <G6Picture g6Data={deviceData}/> : <></>}
Copy after login

Achieve the effect

Can react be used with g6?

The complete code and partial explanation are as follows:

Demo.js

import G6 from &#39;@antv/g6&#39;;
import React, {useEffect} from "react";
import groupBy from 'lodash/groupBy'
import router from "umi/router";
function dealData(data) {//数据处理函数
  const dataGroup = groupBy(data, (item) => [item.chipGroupName])
  const nodes = [];
  const edges = [];
  let index = 0;
  nodes.push({id: `node${index}`, size: 90, label: "芯片组管理", edgeStrength: true})
  for (const key in dataGroup) {
    index += 1;
    nodes.push({id: `node${index}`, size: 60, label: key, edgeStrength: false, isLeaf: true})
    edges.push({source: `node0`, target: `node${index}`, label: '芯片', routerFlag: 0})
    if (dataGroup[key]) {
      const indexTemp = index;
      dataGroup[key].map((item) => {
        index += 1;
        nodes.push({id: `node${index}`, size: 40, label: item.name, edgeStrength: false})
        edges.push({source: `node${indexTemp}`, target: `node${index}`, label: "产品", routerFlag: 1})
      })
    }
  }
  const returnData = {
    nodes: [...nodes],
    edges: [...edges],
  }
  return returnData;
}
export default function (props) {//props为传入的参数
  const ref = React.useRef(null)
  let graph = null;
  useEffect(() => {
    const {g6Data} = props;
    const data = dealData(g6Data);
    const width = document.getElementById('test').clientWidth;//获取当前宽度
    if (!graph) {
      graph = new G6.Graph({//生成关系图实例
        container: ref.current,//获取真实的DOM节点
        width: width < 1000 ? 387 : width,//根据所需大小定义高度、宽度
        height: width < 1000 ? 220 : 550,
        layout: {//根据要求所需及官方API文档配置
          type: 'force',
          preventOverlap: true,
          linkDistance: (d) => {
            if (d.source.id === 'node0') {
              return 10;
            }
            return 80;
          },
          nodeStrength: (d) => {//根据要求所需及官方API文档配置
            if (d.isLeaf) {
              return 200;
            }
            return -500;
          },
          edgeStrength: (d) => {//根据要求所需及官方API文档配置
            if (d.source.edgeStrength) {
              return 0.1;
            }
            return 0.8;
          },
        },
        defaultNode: {//根据要求所需及官方API文档配置
          color: '#5B8FF9',
        },
        edgeStateStyles: {//根据要求所需及官方API文档配置
          highlight: {
            stroke: '#5B8FF9' // 这个颜色可以根据个人喜好进行修改
          }
        },
        modes: {//根据要求所需及官方API文档配置
          default: ['drag-canvas', 'zoom-canvas'],
        },
      });
    }
    const {nodes} = data;
    graph.data({//绑定数据
      nodes,
      edges: data.edges.map((edge, i) => {
        edge.id = `edge${i}`;
        return Object.assign({}, edge);
      }),
    });
    graph.render();//渲染图形
//下面为交互事件配置及操作函数
    graph.on('node:dragstart', (e) => {
      graph.layout();
      refreshDragedNodePosition(e);
    });
    graph.on('node:drag', (e) => {
      refreshDragedNodePosition(e);
    });
    graph.on('node:dragend', (e) => {
      e.item.get('model').fx = null;
      e.item.get('model').fy = null;
    });
    graph.zoom(width < 1000 ? 0.7 : 1, {x: 300, y: 300});
    graph.on('node:mouseenter', (ev) => {
      const node = ev.item;
      const edges = node.getEdges();
      const model = node.getModel();
      const size = model.size * 1.2;
      graph.updateItem(node, {
        size,
      });
      edges.forEach((edge) => {
        graph.setItemState(edge, 'highlight', true)
      });
    });
    graph.on('node:click', (e) => {
      router.push({pathname: `/DeviceSetting/ChipsetManagement`})
    });
    graph.on('node:mouseleave', (ev) => {
      const node = ev.item;
      const edges = node.getEdges();
      const model = node.getModel();
      const size = model.size / 1.2;
      graph.updateItem(node, {
        size,
      });
      edges.forEach((edge) => graph.setItemState(edge, 'highlight', false));
    });
    function refreshDragedNodePosition(e) {
      const model = e.item.get('model');
      model.fx = e.x;
      model.fy = e.y;
    }
  }, []);
  return <>
    <div ref={ref} id="test"/>
  ;
};
Copy after login

Specific use of Demo’s js file :

import G6Picture from './Demo'
render(
    return(
        <>
            {deviceData.length ? <G6Picture g6Data={deviceData}/> : <></>}
        
    )
)
Copy after login

Recommended learning: "react video tutorial"

The above is the detailed content of Can react be used with g6?. 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)

How to build a real-time chat app with React and WebSocket How to build a real-time chat app with React and WebSocket Sep 26, 2023 pm 07:46 PM

How to build a real-time chat application using React and WebSocket Introduction: With the rapid development of the Internet, real-time communication has attracted more and more attention. Live chat apps have become an integral part of modern social and work life. This article will introduce how to build a simple real-time chat application using React and WebSocket, and provide specific code examples. 1. Technical preparation Before starting to build a real-time chat application, we need to prepare the following technologies and tools: React: one for building

Guide to React front-end and back-end separation: How to achieve decoupling and independent deployment of front-end and back-end Guide to React front-end and back-end separation: How to achieve decoupling and independent deployment of front-end and back-end Sep 28, 2023 am 10:48 AM

React front-end and back-end separation guide: How to achieve front-end and back-end decoupling and independent deployment, specific code examples are required In today's web development environment, front-end and back-end separation has become a trend. By separating front-end and back-end code, development work can be made more flexible, efficient, and facilitate team collaboration. This article will introduce how to use React to achieve front-end and back-end separation, thereby achieving the goals of decoupling and independent deployment. First, we need to understand what front-end and back-end separation is. In the traditional web development model, the front-end and back-end are coupled

How to build simple and easy-to-use web applications with React and Flask How to build simple and easy-to-use web applications with React and Flask Sep 27, 2023 am 11:09 AM

How to use React and Flask to build simple and easy-to-use web applications Introduction: With the development of the Internet, the needs of web applications are becoming more and more diverse and complex. In order to meet user requirements for ease of use and performance, it is becoming increasingly important to use modern technology stacks to build network applications. React and Flask are two very popular frameworks for front-end and back-end development, and they work well together to build simple and easy-to-use web applications. This article will detail how to leverage React and Flask

How to build a reliable messaging app with React and RabbitMQ How to build a reliable messaging app with React and RabbitMQ Sep 28, 2023 pm 08:24 PM

How to build a reliable messaging application with React and RabbitMQ Introduction: Modern applications need to support reliable messaging to achieve features such as real-time updates and data synchronization. React is a popular JavaScript library for building user interfaces, while RabbitMQ is a reliable messaging middleware. This article will introduce how to combine React and RabbitMQ to build a reliable messaging application, and provide specific code examples. RabbitMQ overview:

React code debugging guide: How to quickly locate and solve front-end bugs React code debugging guide: How to quickly locate and solve front-end bugs Sep 26, 2023 pm 02:25 PM

React code debugging guide: How to quickly locate and resolve front-end bugs Introduction: When developing React applications, you often encounter a variety of bugs that may crash the application or cause incorrect behavior. Therefore, mastering debugging skills is an essential ability for every React developer. This article will introduce some practical techniques for locating and solving front-end bugs, and provide specific code examples to help readers quickly locate and solve bugs in React applications. 1. Selection of debugging tools: In Re

React Router User Guide: How to implement front-end routing control React Router User Guide: How to implement front-end routing control Sep 29, 2023 pm 05:45 PM

ReactRouter User Guide: How to Implement Front-End Routing Control With the popularity of single-page applications, front-end routing has become an important part that cannot be ignored. As the most popular routing library in the React ecosystem, ReactRouter provides rich functions and easy-to-use APIs, making the implementation of front-end routing very simple and flexible. This article will introduce how to use ReactRouter and provide some specific code examples. To install ReactRouter first, we need

How to build a fast data analysis application using React and Google BigQuery How to build a fast data analysis application using React and Google BigQuery Sep 26, 2023 pm 06:12 PM

How to use React and Google BigQuery to build fast data analysis applications Introduction: In today's era of information explosion, data analysis has become an indispensable link in various industries. Among them, building fast and efficient data analysis applications has become the goal pursued by many companies and individuals. This article will introduce how to use React and Google BigQuery to build a fast data analysis application, and provide detailed code examples. 1. Overview React is a tool for building

How to package and deploy front-end applications using React and Docker How to package and deploy front-end applications using React and Docker Sep 26, 2023 pm 03:14 PM

How to use React and Docker to package and deploy front-end applications. Packaging and deployment of front-end applications is a very important part of project development. With the rapid development of modern front-end frameworks, React has become the first choice for many front-end developers. As a containerization solution, Docker can greatly simplify the application deployment process. This article will introduce how to use React and Docker to package and deploy front-end applications, and provide specific code examples. 1. Preparation Before starting, we need to install

See all articles