A best practice is to isolate the work of the API from the UI components that you are going to build. This is nice way to maintain a separation of concerns in your development.
In this example, we are going to do the work of creating our map in
Looking at this code snippet, you can see that this is where we create our map and view, except 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.
WebMap component, we are going to take advantage of a brand new feature to React called hooks. Hooks are still a React proposal and are scheduled to be finalized in early 2019, so 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 hook is run after the React component is rendered. This makes it perfectly suited for us to use to dynamically load our
data/app.js module and run the
initialize function we created earlier. But how do we get the element for our component? That’s where
useRef comes in!
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
Looking at this sample, you can see that we use the
Now we can render this component like any other React component in our application.
Your finished application should look like this, which is a React component that displays a WebMap.