[Fan Wai] ArcGIS JS API 4.14 is used in React

This paper mainly introduces how to use ArcGIS JS API for development in the React project. The JS API used in this paper is the latest version of ArcGIS JS API 4.14. It mainly instantiates a two-dimensional map with JS API in the React project demo.

summary

For a long time ago, when using ArcGIS JS API (hereinafter referred to as "JS API") to develop WebGIS system, it was still developed based on traditional front-end framework and various front-end technologies. These frameworks and technologies you have probably used: Dojo, jQuery, Bootstrap, CommonJS, etc. When developing with these traditional technical frameworks combined with JS API, we introduce JS API through < script > and < style > tags in the HTML page of the system. The usual way is to index on the home page HTML. The code is as follows:

<link rel="stylesheet" href="http://localhost/4.14/esri/themes/light/main.css" />
<script src="http://localhost/4.14/init.js"></script>

At present, with the continuous development of front-end technology, front-end development technologies such as React and Vue have become the standard configuration of a front-end developer. As GISer, we are no exception. When developing many WebGIS project systems, we will choose these mainstream development technologies, among which React and Vue are the most used. So this article mainly introduces how to use React combined with JS API to develop our project system.

Technical basis before start

  • Have some basic knowledge of React, be familiar with ES6 and JSX syntax
  • The computer has NodeJS installed. I've heard of npm

Operation steps

Environmental preparation

Before today's introduction, we need to prepare the development environment. This article has only one requirement for the development environment: NodeJS environment. If you don't have this environment, please see the following for installation; If you have this environment on the machine, please skip this section and read from section 2. 1.1. NodeJS environment installation 1.1.1. Enter NodeJS official website( https://nodejs.org/en/ )Download the latest version of NodeJS. It is recommended to download the LTS version, which is stable and has long-term official support for updating, as shown in the figure:

1.1.2 after downloading the installation package, double-click the installation package to pop up the installation interface. After selecting the corresponding installation directory, we can click the [Next] button all the way. There is nothing special to pay attention to in the middle process. 1.1.3 after the installation is completed, we open the command line window and check whether the installation is successful through the following commands. If the following version number information appears, it indicates that the installation and deployment of NodeJS environment is successful:

node -v
npm -v

Here, someone may ask about the relationship between NodeJS and npm. In fact, NodeJS is a running environment of JavaScript. It encapsulates Google V8 engine and is a server-side JS interpreter. npm is a package manager of NodeJS. If we need to use any plug-in in development, we need to search, download and install it into NodeJS environment before we can use this plug-in to develop and complete a requirement. This process is quite cumbersome. With the npm package manager, we only need to run the command line under the project root directory, and then install the required plug-ins into the project or NodeJS environment with one click through the npm installation command. This is a very convenient thing. Moreover, many gods upload their developed wheels to the npm website, so we can directly install the plug-ins we need, There is no need to search, download and install. 1.1.4. Here we install the NodeJS environment. To put it bluntly, we only install the npm package manager. 1.1.5 after installing the NodeJS environment, someone will ask whether we want to install the React environment like Vue. In fact, it is not necessary here. Our React scaffold tool has been installed when installing NodeJS. It is an evolutionary version of npm, npx, through which we create React projects later. So far, our environment preparation has been completed. Next, let's get to today's topic and use React combined with JS API to develop.

Initialize project demo

2.1. Create a new folder in the appropriate directory, then open the command line tool in this folder, and create a basic React project demo through the following commands, as follows:

npx create-react-app reactjsapi414demo

The above command uses the scaffolding tool of React to initialize a project demo. The demo name is "reactjsapi414demo", which can be named at will. After entering the above command and pressing enter, the plug-in installation and project initialization will be carried out. 2.2 after the project initialization, we use the command prompt in the command line to enter the project root directory, then start the project through the prompt command, and view it in the browser through the address localhost:3000, as follows:

cd .\reactjsapi414demo\
npm start

2.3. At this time, the initialization project operation has been completed. We created a basic react project demo through react scaffolding. Next, we use this demo to introduce how to develop and use JS API in combination with react.

Combined development of ArcGIS JS API and React

The above process has completed the environment installation, deployment and project initialization. Next, we will introduce the development of JS API. 3.1. When using JS API in React project, it is not like the traditional development method in index JS and CSS files are introduced into HTML to use js API. Instead, a middleware called "ESRI loader" is used to seamlessly connect our JS API with React project. 3.2. In the command line, use Ctrl+C to stop the project, and then use the following command to install ESRI loader, as follows:

npm install esri-loader --save-dev

3.3 after installation, restart the project with the command npm start, and then open the project code initialized by us with the editor. The webStrom editor is used here. You can use the editors such as Hbuilder, SublimeText3, VS Code, etc. without mandatory requirements, as follows:

3.4. Then open package. Under the root directory of the project JSON file. In this file, we can see the ESRI loader plug-in just installed. At this time, v2.0 is used Version 13.0, as follows:

3.5. Next, in the src folder under the root directory of the project, we modify app JS file to introduce how to use JS API development in React. As follows, let's delete app JS file contains redundant HTML tags and some JS code, and then modify the default functional component to the class component writing method. Finally, the file code is as follows:

3.6. Instead of creating a new tag here, we directly add an id attribute with the same name to the div whose class is "app" to instantiate a map. Next, we modify the label style of the div whose id is "app". The code is as follows:

#app {
  position: absolute;
  width: 100%;
  height: 100%;
}

3.7. Then load the ESRI loader plug-in installed by us, as follows:

import esriLoader from 'esri-loader';

3.8 after introducing ESRI loader, let's connect our project system with JS API. Here, we must understand a concept: when we use js API in React, the interfaces we call are those we traditionally develop. ESRI loader only acts as a bridge here, so we should not mistakenly think that ESRI loader is also a development package. In other words, the JS API development package you finally use is still the development package deployed locally or on the official website of JS API, not the development package in ESRI loader. Before connection, we first create a componentDidMount life cycle function, and then initialize the map in this function. The code is as follows:

import React,{Component} from 'react';
import esriLoader from 'esri-loader';
import './App.css';
class App extends Component{
    state = {
    }
    componentDidMount = () => {
        const _self = this;
        const options = {
            url: 'https://js.arcgis.com/4.14/init.js', / / the API address here can be the CDN provided on the official website or the address of offline deployment can be configured here
            css: 'https://js.arcgis.com/4.14/esri/themes/light/main.css'
        };
        esriLoader.loadModules([], options) // Pass in the class you want to use
            .then(([]) => {
                // doSomeThing
            })
            .catch(err => {
                console.error('Map initialization failed', err);
            })
    }
    render () {
        return (
            <div className='App' id='app'>
            </div>
        )
    }
}
export default App;

Through the above code, we have made a connection between our project system code and JS API. In fact, we have introduced JS API into our React project. Next, we will develop JS API. 3.9 this paper mainly introduces how to use js API development by instantiating a map. The next operation is similar to our traditional development method. First load the corresponding JS API module, and then instantiate each module, as shown below:

        esriLoader.loadModules([
            "esri/Map",
            "esri/views/MapView"], options) // Pass in the class you want to use
            .then(([Map,
                       MapView
                   ]) => {
                // doSomeThing
                let map = new Map({
                    basemap: 'osm'
                });
                let view = new MapView({
                    container: "app",
                    map: map,
                    center: [104.072044,30.663279],
                    zoom: 10
                });
            })
            .catch(err => {
                console.error('Map initialization failed', err);
            })

3.10. Through the above steps, a two-dimensional map is instantiated, and the final effect is as follows:

summary

This paper introduces in detail the process of building the basic project demo of React to the introduction of JS API and finally generating a two-dimensional map. This article is suitable for those who have a certain foundation of React and JS API development. The JS API we use in this article is the JS API of the official website. You can also change the API address to local. You only need to modify the attribute value of the options object, similar to the following:

const options = {      //Define an object that contains the js development package and css style file in the JS API
    url: 'http://localhost/4.14/init.js',
    css: 'http://localhost/4.14/esri/themes/light/main.css',
};

By modifying the above code, the reference address of JS API is changed to the local address, but the cross domain problem needs to be paid attention to when running here. If you encounter a cross domain problem, you can solve it by configuring the React configuration file. The specific operation is not within the scope of this article and can be solved by Baidu itself. If you encounter any questions during the combined development of React and JS API, please contact the blogger to answer.

Attachment:

Full code of project demo:

https://github.com/xuqwCloud/use_of_arcgis_js_api_in_react

App.js all codes:

import React,{Component} from 'react';
import esriLoader from 'esri-loader';
import './App.css';
class App extends Component{
    state = {
    }
    componentDidMount = () => {
        const _self = this;
        const options = {
            url: 'https://js.arcgis.com/4.14/init.js', / / the API address here can be the CDN provided on the official website or the address of offline deployment can be configured here
            css: 'https://js.arcgis.com/4.14/esri/themes/light/main.css'
        };
        esriLoader.loadModules([
            "esri/Map",
            "esri/views/MapView"], options) // Pass in the class you want to use
            .then(([Map,
                       MapView
                   ]) => {
                // doSomeThing
                let map = new Map({
                    basemap: 'osm'
                });
                let view = new MapView({
                    container: "app",
                    map: map,
                    center: [104.072044,30.663279],
                    zoom: 10
                });
            })
            .catch(err => {
                console.error('Map initialization failed', err);
            })
    }
    render () {
        return (
            <div className='App' id='app'>
            </div>
        )
    }
}
export default App;

Added by besbajah on Mon, 21 Feb 2022 09:44:58 +0200