Mapbox with React
Last updated
Last updated
allows us to display a customized map on our own websites (provided we stay within limits) - to do so, we need:
Javascript library
Node.js with npm installed
account (optional for deployment)
Some React and JavaScript experience
Please ensure that only the desired website URL(s) may use your Mapbox access token!
In your project folder:
Use npm init
to create a package.json
file at the root
Create a public
folder for the final product and create the files:
index.html
where the final product will display
index.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
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)
We'll go into the public
folder and open the index.html
file
The following lines will minimally setup our map interface:
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 the src
folder
the line with App
contains our App logic
finally, we have our app as the remainder of the file
all that React code will populate the <div id="app"></div>
of the index.html
file
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 name
To access that .env
variable, we use process.env.REACT_APP_
in our JS file
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 changes
a return
statement that will provide a container for the map
recall the useRef
hook at the top of the Map
functional component
Lastly, we just need to add some CSS in src/index.css
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
Ensure you have your own API key from
Please refer to to see how to make this map appear on the Internet: