Using Opencage Gecoder API with REACT
Tags: javascript, react, geocoder, opencage
Published: 2020-03-22 09:07:43

Photo by [Kelsey Knight](https://unsplash.com/photos/SFRw5GChoLA) on [Unsplash](https://unsplash.com/?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)

:new: Newer version available [Using OpenCage Gecoder API with React (2nd-edition)](https://dev.to/tsamaya/using-opencage-gecoder-api-with-react-2nd-edition-35bh)

This post was previously published on [Medium](https://medium.com/@tsamaya/using-opencage-gecoder-api-with-react-e4fdc4d79da0)

Overview
========

In this tutorial, we will discuss about the integration of [Opencage](https://opencagedata.com/) API into a [React](https://reactjs.org/) application.

The prerequisites are, of course, a OpenCage API key, (if you don’t have one, simply use this free registration [link](https://opencagedata.com/users/sign_up)), a [node](https://nodejs.org/) platform with [yarn](https://yarnpkg.com/) or [npm](https://www.npmjs.com/get-npm); and finally your favourite IDE or Text Editor.

I assume you are familiar with JavaScript. In this tutorial, we’re going to use some ES6 features like [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions), [classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), [let](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let), and [const](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) statements.

This tutorial is not about setting up a build environment for React, so for the easy use, we will use [create-react-app](https://facebook.github.io/create-react-app/).

Before we start, here is the [source code](https://github.com/tsamaya/opencage-react-guide). And a live version can be found [here](https://unruffled-kirch-3cd76e.netlify.com/).

Setup the environment
=====================

As current node version, when writing this guide, is 10.12; I assume you can use `npx` as it is available since version 5.2.

```
$ npx create-react-app opencage-react-app
```

it outputs :

```
Creating a new React app in \[...\]/opencage-react-app.Installing packages. This might take a couple of minutes.  
Installing react, react-dom, and react-scripts...yarn add v1.10.1  
\[1/4\] 🔍  Resolving packages...  
\[2/4\] 🚚  Fetching packages...  
\[3/4\] 🔗  Linking dependencies...  
\[4/4\] 📃  Building fresh packages...  
success Saved lockfile.  
success Saved 11 new dependencies.  
info Direct dependencies  
├─ react-dom@16.5.2  
├─ react-scripts@2.0.5  
└─ react@16.5.2  
info All dependencies  
├─ babel-plugin-dynamic-import-node@2.2.0  
├─ babel-preset-react-app@5.0.4  
├─ confusing-browser-globals@1.0.4  
├─ eslint-config-react-app@3.0.4  
├─ eslint-plugin-jsx-a11y@6.1.2  
├─ object.assign@4.1.0  
├─ react-dev-utils@6.0.5  
├─ react-dom@16.5.2  
├─ react-error-overlay@5.0.5  
├─ react-scripts@2.0.5  
└─ react@16.5.2  
✨  Done in 79.89s.Initialized a git repository.Success! Created opencage-react-app at \[...\]/opencage-react-app  
Inside that directory, you can run several commands: yarn start  
    Starts the development server. yarn build  
    Bundles the app into static files for production. yarn test  
    Starts the test runner. yarn eject  
    Removes this tool and copies build dependencies, configuration files  
    and scripts into the app directory. If you do this, you can’t go back!We suggest that you begin by typing: cd opencage-react-app  
  yarn startHappy hacking!
```

Start hacking
=============

First part
==========

Let’s do the suggested commands

```
$ cd opencage-react-app  
$ yarn start
```

The project is built in development mode and it opens your favourite browser on [http://localhost:3000](http://localhost:3000/).

![create-react-app-start](https://raw.githubusercontent.com/tsamaya/opencage-react-guide/master/resources/create-react-app-start.png)

The page will automatically reload if you make changes to the code. So let’s do it.

First of all download [opencage svg logo](https://raw.githubusercontent.com/tsamaya/opencage-react-guide/master/resources/opencage-white.svg) and copy it to the `src/` folder

Open your IDE or Text Editor with the folder `opencage-react-app`

Edit the file `./src/App.js`

replace

```
import logo from './logo.svg';
```

with

```
import logo from './opencage-white.svg';
```

The app is rebuilt and instead of the atomic react logo, you should now have a Open Cage logo.

use `CTRL + C` to stop the development server.

We will now add dependencies to the project.

First the style, you can pick up your favourite CSS framework (flexbox, bootstrap or material UI), for this tutorial I picked up [Bulma](https://github.com/tsamaya/opencage-react-guide/blob/master) as it is javascript free, then no react wrapper is needed to keep this tutorial simple and focused only on opencage geocode API integration.

```
$ yarn add bulma
```

it outputs

```
yarn add v1.10.1  
\[1/4\] 🔍  Resolving packages...  
\[2/4\] 🚚  Fetching packages...  
\[3/4\] 🔗  Linking dependencies...  
\[4/4\] 📃  Building fresh packages...success Saved lockfile.  
success Saved 3 new dependencies.  
info Direct dependencies  
├─ bulma@0.7.2  
├─ react-dom@16.5.2  
└─ react@16.5.2  
info All dependencies  
├─ bulma@0.7.2  
├─ react-dom@16.5.2  
└─ react@16.5.2  
✨  Done in 8.61s.
```

let’s create an Header component:

Rename `App.css` into `Header.css`. Then edit `Header.css`, we will avoid being see sick with the infinite loop animation and place the center text in the header only. The header will be a header not whole view port page.

{% gist https://gist.github.com/tsamaya/23dd54330b72ceaaf82b0ca8d365355d %}

Create `./src/Header.js` file:

{% gist https://gist.github.com/tsamaya/9db2a0bf0eebe9ef68f8a418e8977092 %}

Edit `./src/index.js`, adding

```
import 'bulma/css/bulma.css';
```

after

```
import './index.css';
```

now edit `App.js`, we first use the `Header` Component and then we prepare 2 columns.

{% gist https://gist.github.com/tsamaya/4f6f88e472820e20076d85cc0950c90f %}

Now add packages dependencies like the opencage API client, LeafletJS, and classnames:

```
$ yarn add opencage-api-client leaflet classnames
```

*   [opencage-api-client](https://github.com/tsamaya/opencage-api-client) is the client library for Opencage Geocoder API
*   [LeafletJS](https://leafletjs.com/) is the well-known web mapping API
*   [classnames](https://github.com/JedWatson/classnames) is a javascript utility lib to help build className attributes

We can start the dev server with `$ yarn start`

For now the app looks like this

![screenshot-1](https://raw.githubusercontent.com/tsamaya/opencage-react-guide/master/resources/screenshot-1.png)

In the first column we will set up the form with the search input parameters. In the second column, we will have the results as multiple tabs, starting with the readable results (formatted address and coordinates), and a second tab with the raw JSON result from the API. As you can see in the following design, we will create two main components and `GeocodingForm`and `GeocodingResults`

![design](https://raw.githubusercontent.com/tsamaya/opencage-react-guide/master/resources/design-1.png)

Create a file `./src/GeocodingForm.js`

{% gist https://gist.github.com/tsamaya/9038740e3f4247af124a77950c06e3a9 %}

Then create a file `./src/GeocodingResults.js`

{% gist https://gist.github.com/tsamaya/a2025b3ee6828b30d2754b41b3eeaf2c %}

We need to create files `./src/ResultList.js` and `./src/ResultJSON.js`

{% gist https://gist.github.com/tsamaya/a6d8ec4d25d56e04e9bc2a7db4a0d31f %}

{% gist https://gist.github.com/tsamaya/bf54623f7585165899cf41a5080272f1 %}

To finish the first part, wire the application with those two main components (GeocodingForm and GeocodingResults)

Edit the `./src/App.js` file, first the imports:

{% gist https://gist.github.com/tsamaya/3dfab1000812ecfc572753229bc0f6c1 %}

now add a constructor

{% gist https://gist.github.com/tsamaya/2c13ce21dd9d511e841e6e84535fc473 %}

the App handles input text changes and the submit.

So first add the `handleChange` method

{% gist https://gist.github.com/tsamaya/0a74902135b74a644f5778bf7c4eb077 %}

Followed by the `handleSubmit` method

{% gist https://gist.github.com/tsamaya/e9ffc1d9d9235d4d777eeb57cbfe4e5e %}

Last touch for this first part, we add the main components in the `render` method:

{% gist https://gist.github.com/tsamaya/74bc656c21a508bd7b149e547178be24 %}

Here is what the app now looks like

![screenshot-2](https://raw.githubusercontent.com/tsamaya/opencage-react-guide/master/resources/screenshot-2.png)

Second part
===========

In this part we will add a map tab in the result section.

First let’s create a `./src/ResultMap.js` file :

{% gist https://gist.github.com/tsamaya/3a3168cec77120a565b3a869b05b8379 %}

Download the pin icon from [marker-icon-red.png](https://github.com/tsamaya/opencage-react-guide/blob/master/public/marker-icon-red.png) and save it to `public/` folder.

As the map needs a height, we create a `./src/ResultMap.css` file :

{% gist https://gist.github.com/tsamaya/4aa697440777fa1f6a996a73a1a6d164 %}

Back in `./src/GeocodingResuls.js` add the tab in the `ul` _s_ection

{% gist https://gist.github.com/tsamaya/ea8ce6d9f2fab63467458add4eb3b217 %}

and with the other results content add the map:

{% gist https://gist.github.com/tsamaya/162645cb3ba884b95b03d621a981c396 %}

The app now contains a map

![screenshot-3](https://raw.githubusercontent.com/tsamaya/opencage-react-guide/master/resources/screenshot-3.png)

I really hope this was helpful for you. If it was, please, do let me know so that I can write more posts like this. You can always reach me out on [Twitter](https://twitter.com/arferrand)  and again if you followed this tutorial along till the end, I am really proud of you guys.

Resources
---------

*   Opencage Data Geocoder: [https://opencagedata.com/](https://opencagedata.com/)
*   Source code repository on github : [https://github.com/tsamaya/opencage-react-guide](https://github.com/tsamaya/opencage-react-guide)
*   Demo version on netlify : [https://unruffled-kirch-3cd76e.netlify.com/](https://unruffled-kirch-3cd76e.netlify.com/)