Skip to main content

Add to your React Application

This example deploys Address Finder with React.

Install

npm install --save @ideal-postcodes/address-finder

Import Address Finder

Add the following to your component.

import { AddressFinder } from "@ideal-postcodes/address-finder";
import { useEffect, useState, useRef } from "react";

Initializing Component State

Within your component, use a state hook to capture the address elements you need.

const [state, setState] = useState({
line_1: "",
line_2: "",
line_3: "",
post_town: "",
postcode: "",
country: ""
});

Initialise Address Finder within useEffect

// The useRef hook is used to persist the flag shouldRender across re-renders, ensuring the address finder is initialized only once.
const shouldRender = useRef(true);

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

AddressFinder.watch({
inputField: "#searchField",
apiKey: "ak_test",
onAddressRetrieved: (address) => {
setState({
line_1: address.line_1,
line_2: address.line_2,
line_3: address.line_3,
post_town: address.post_town,
postcode: address.postcode,
country: address.country,
});
},
});
}, []);
info

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

Your Address Inputs

Your search field should have an id which matches inputField (in this instance it's "searchField").

You can create a typical React form by binding the component's state to the relevant input field.

return (
<form className="App">
<h1>Address Finder React Demo</h1>
<div>
<input
placeholder="Start typing find your address"
id="searchField"
type="text"
/>
</div>
<div>
<label htmlFor="line_1">Address Line One</label>
<input 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...