@ubilabs/mapbox-react-hooks
TypeScript icon, indicating that this package has built-in type declarations

1.0.7 • Public • Published

Mapbox React Hooks npm version

This is a JavaScript library to easily implement a Mapbox map into your React application. It comes with a collection of React hooks to access the Mapbox map instance all over your components and to handle some common interactions with the map.

Table of contents

Requirements

You need to have React 16.8.0 or later installed to use the Hooks API.

Installation

npm install @ubilabs/mapbox-react-hooks -S

Usage

Import the MapProvider and wrap it around your components. Make sure all components that should have access to the Mapbox map instance are nested inside of the MapProvider.

import React, {useState, useCallback, forwardRef} from 'react';
import {MapProvider} from '@ubilabs/mapbox-react-hooks';

const MapCanvas = React.forwardRef((props, ref) => (
  <div ref={ref} />
));

function App() {
  const [mapContainer, setMapContainer] = useState(null);
  const mapRef = useCallback((node) => {
    node && setMapContainer(node);
  }, []);

  return (
    <MapProvider
      mapContainer={mapContainer}
      config={{
        accessToken: MAPBOX_ACCESS_TOKEN,
        ...
      }}
      onLoad={(map) => {/* Do something with the map */}}
    >
      <React.StrictMode>
        <MapCanvas ref={mapRef} />
      </React.StrictMode>
    </MapProvider>
  );
}

export default App;

The MapProvider makes the Mapbox map instance available to any nested components with the useMap hook.

import React from 'react';
import {useMap} from 'mapbox-react-hooks';

const MyComponent = () => {
  const mapInstance = useMap();

  // Do something with the Mapbox map instance

  return (...);
};

Example

Edit Codesandbox

MapProvider

A provider component to wrap around all components that should have access to the Mapbox map instance. (read more)

Hooks

useMap

React hook to get the map instance. (read more)

useGeoJSONSource

React hook to add sources and layers to the map instance and to properly clean them up. The sources will be updated with new data without reapplying all layers again. (read more)

useMapLayerClick

React hook to handle a click on a map layer. (read more)

useMapLayerHover

React hook to handle a hover over a map layer. (read more)

Publish (only for maintainers)

npm publish --access public

Package Sidebar

Install

npm i @ubilabs/mapbox-react-hooks

Weekly Downloads

6

Version

1.0.7

License

ISC

Unpacked Size

48.1 kB

Total Files

28

Last publish

Collaborators

  • aemkei
  • pwambach
  • mrmetalwood
  • usefulthink
  • theamazingpt
  • rich_pb
  • ubilabs-bot