By: Tristen Brown

When we build web applications at Mapbox, we often turn to React and Mapbox GL JS. The libraries work powerfully in combination, and I’d like to share some techniques for connecting the two.

The power of React lies in being an abstraction on top of the DOM. What’s shown to the user when a component calls render() is conveniently managed internally allowing an implementor to work on higher level tasks like how an interface behaves.

What can be confusing is connecting React with other libraries that manipulate the DOM and manage state (like Mapbox GL JS). How do you communicate between both effectively? It’s common to turn to component wrappers that provide a level of abstraction that hides this confusion away. That technique is effective for enforcing a standardized set of rules passed as props across your application. An example may be a modal component. The wrapper permits customization like size or title , and the technical details that should always be the same (event handling of key bindings or accessibility) are tucked away in the lower level modal component.

So it’s natural to look for a <Mapbox /> component within the React ecosystem (see react-map-gl or react-mapbox-gl as example). The goals however of a Modal component are small and applying this same technique to a feature rich library is a high tradeoff. If you are missing functionality, it’s up to the maintainer to expand support through additional props.

Thankfully Mapbox GL JS works well without a wrapper abstraction. It’s pretty easy for third-party libraries to work alongside React!

The entry point to initialize a map is through a single element provided in the return statement of your render function. Here’s a quick example:

JSX creates the div container and the map is continuously updated through lifecycle methods. The key is that ref attribute. The map is initialized within componentDidMount and its container value is set as the assignment of this.mapContainer which is React’s way of providing direct access to the DOM node.

Let’s explore some more in-depth examples:

Basic example