In this example, we are going to do the work of creating our map in data/app.js, shown in Figure 1. Looking at this code snippet, you can see that this is where we create our map and view, but we do not attach our view to the page right away. We export a function called initialize that takes an argument for the container, which is a DOM element where our MapView will be displayed. This DOM element will come from the React component that we will write.
For the WebMap component, we are going to take advantage of a brand new feature in React called hooks that lets you use state and other React features without writing a class. Hooks are still a React proposal that is scheduled to be finalized in early 2019. I wouldn’t recommend using them in production just yet, but I thought it would be fun to use them for this example. There are numerous React hooks you can use, but for our purposes, we are only concerned with two: useEffect and useRef.
The useEffect hook is run after the React component is rendered. This makes it perfectly suited for dynamically loading our data/app.js module and running the initialize function we created earlier. But how do we get the element for our component? That’s where useRef comes in.
The useRef hook creates an object that exists for as long as the component is mounted. In our case, we want to keep track of the DOM element that is going to be created by our React component. We can see what this looks like in components/WebMap.js, shown in Figure 2.
In your finished application, a React component displays a WebMap, as shown in Figure 4.