Skip to main content

Custom Form - Advanced

Using the Custom Form experience gives you complete control over the appearance and functionality (UI/UX).

In our previous examples we covered adding the component and styling it. In these examples we'll go over a few different scenarios for improving UX.

info

This guide assumes you've already gone through the Basic implementation here.

Submission Handling

Using the onSuccess event prop will let us know when the form was submitted successfully.

Let's add in a small component that renders after success.

Example
import { CustomForm, useFormApiRef } from '@vtagz/web-sdk-react';

function Index() {
const apiRef = useFormApiRef();
const [success, setSuccess] = useState(false);
if (success) {
return (
<div>Subscribed!</div>
);
}
return (
<form>
<CustomForm
link='YOUR_CAMPAIGN_LINK'
apiRef={apiRef}
onSuccess={() => {
setSuccess(true);
}}
/>
<button type="button" onClick={() => apiRef.current.submit()} >
Submit
</button>
</form>
);
}
Result

After submitting with a valid number, we'll see our "Subscribed!" message.

Error Handling

Using the onError and onInputChange event props we can check the validity of the current input.

Let's add these along with a custom error component.

Example
import { CustomForm, useFormApiRef } from '@vtagz/web-sdk-react';

function Index() {
const apiRef = useFormApiRef();
const [hasError, setHasError] = useState(false);
const [success, setSuccess] = useState(false);
if (success) {
return (
<div>Subscribed!</div>
);
}
return (
<form>
<CustomForm
link='YOUR_CAMPAIGN_LINK'
apiRef={apiRef}
onSuccess={() => {
setSuccess(true);
}}
onInputChange={(data) => {
if (data.isValid) {
setHasError(false);
}
}}
onError={(msg) => {
setHasError(true);
}}
/>
{ hasError && (
<div className='error'>Check your form for errors</div>
)}
<button type="button" onClick={() => apiRef.current.submit()} >
Submit
</button>
</form>
);
}
Result

Now if we put in a bad number (like 12345) and press "submit" we will see our new error message.

Controlling the input state

The useFormApiRef hook exposes the input state interface allowing you to disable/enable the input, as well as a few other options.

Let's use the enable() and disable() methods to control the flow with a required checkbox field.

Example
import { CustomForm, useFormApiRef } from '@vtagz/web-sdk-react';

function Index() {
const apiRef = useFormApiRef();
const [requiredChecked, setRequiredChecked] = useState(false);

useEffect(() => {
if (requiredChecked) {
apiRef.current.input.enable();
} else {
apiRef.current.input.disable();
}
}, [requiredChecked]);

return (
<form>
<div>
<input
type='checkbox'
onChange={(e) => {
setRequiredChecked(e.target.checked);
}}
required
/>
<div>Some required checkbox field</div>
</div>
<CustomForm
link='YOUR_CAMPAIGN_LINK'
apiRef={apiRef}
/>
<button
type="button"
onClick={() => apiRef.current.submit()}
disabled={!requiredChecked}
>
Submit
</button>
</form>
);
}
Result