Skip to main content

Add to your React Application

This example deploys Address Lookup with React

Use in your app

Install

npm install --save @addresszen/address-lookup

Importing Necessary Modules

import "./styles.css";
import React, { useEffect, useState, useRef } from "react";
import { AddressLookup } from "@addresszen/address-lookup";

Initializing Component State

const [state, setState] = useState({
line_1: "",
line_2: "",
city: "",
state: "",
zip_plus_4_code: "",
country: "",
});

Initialize the component state with empty strings for address lines, post town, and postcode.

Preventing Re-initialisation with useRef

const shouldRender = useRef(true);

The useRef hook is used to persist the flag shouldRender across re-renders, ensuring the address Lookup is initialized only once.

Address Lookup Initialisation in useEffect

Copy and paste the code below to Initialize the Address Lookup.

useEffect(() => {
if (shouldRender.current) {
shouldRender.current = false;

AddressLookup.watch({
inputField: "#searchField",
apiKey: "ak_test",
onAddressRetrieved: (address) => {
setState({
line_1: address.line_1,
line_2: address.line_2,
city: address.city,
state: address.state,
zip_plus_4_code: address.zip_plus_4_code,
country: address.country,
});
},
});
}
}, []);
info

Make sure to replace the apikey:ak_test to your apiKey. This can be located on your account.

Form and Input Fields

Enclose your input fields inside a Form.

Each input field is bound to the component's state and has an onChange handler to update the state accordingly.

return (
<form className="App">
<h1>Address Lookup React Demo</h1>
<div>
<input
placeholder="Start typing to try an address"
id="searchField"
type="text"
/>
</div>
<div>
<label htmlFor="line_1">Address Line One</label>
<input
id="line_1"
type="text"
value={state.line_1}
onChange={(e) => setState({ ...state, line_1: e.target.value })}
/>
</div>
{/* Similar divs for other address parts */}
</form>
);
info

If you wish to add an additional field, include the parameter name from our documentation.

Live Demo

Loading...