🗺️Mapbox with React
Mapbox allows us to display a customized map on our own websites (provided we stay within limits) - to do so, we need:
Prerequisites
Mapbox GL Javascript library
Node.js with npm installed
GitHub account (optional for deployment)
Some React and JavaScript experience
Please ensure that only the desired website URL(s) may use your Mapbox access token!
Setup
In your project folder:
Use
npm init
to create apackage.json
file at the rootCreate a
public
folder for the final product and create the files:index.html
where the final product will displayindex.css
to house the styles for index.html
Create an
src
folder and create the files to compile:index.js
for all the React logic
Setting up package.json
package.json
Run the following commands in Terminal
Check if the
package.json
looks something like this:
(Compare the "scripts" object to see if it matches)
Creating the HTML index file
We'll go into the
public
folder and open theindex.html
fileThe following lines will minimally setup our map interface:
Creating the React front-end logic
We'll now go into our
src/index.js
file:
Unpacking the above:
the first two lines deal with React
the third line deals with the Mapbox styling library
the line with
index.css
contains our own styling in thesrc
folderthe line with
App
contains our App logicfinally, we have our app as the remainder of the file
all that React code will populate the
<div id="app"></div>
of theindex.html
file
Initializing the MapBox API key
Now that we have our React Mapbox workspace setup, we will move into the App.js file:
We must now create an
.env
file in the project's root folder:
React needs the
REACT_APP_
part of the variable nameTo access that
.env
variable, we useprocess.env.REACT_APP_
in our JS file
Ensure you have your own API key from https://account.mapbox.com/access-tokens
Initializing the map defaults
We still have to give our map its default values for
geographical coordinates (latitude and longitude)
zoom level
etc.
We shall then kick-start our map, again in
src/App.js
:
In the above, we implemented two things:
a
useEffect
hook that ensures the rendering happens anytime the state changesa
return
statement that will provide a container for the maprecall the
useRef
hook at the top of theMap
functional component
Styling the map
Lastly, we just need to add some CSS in
src/index.css
Running the map
OK, let's test the map!
Go back to Terminal into the project folder and type
$ npm start
When we see a message that says "Compiled successfully!" we can then:
take note of the addresses where we can view in the browser
go to the browser and have a look
Deployment
Please refer to deployment to see how to make this map appear on the Internet:
Last updated