React hooks and components for TownHall form submissions
npm install @townhall-gg/reactbash
npm install @townhall/react
or
pnpm add @townhall/react
or
yarn add @townhall/react
`
Usage
$3
`tsx
import { useTownHallForm } from '@townhall/react'
function ContactForm() {
const { submit, isSubmitting, isSuccess, error } = useTownHallForm('your-form-id')
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
const formData = new FormData(e.currentTarget)
await submit(Object.fromEntries(formData))
}
if (isSuccess) {
return (
Thank you!
Your message has been sent.
)
}
return (
)
}
`
$3
`tsx
function NewsletterForm() {
const { submit, isSubmitting, isSuccess, error, reset } = useTownHallForm('newsletter-form-id')
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
const formData = new FormData(e.currentTarget)
await submit(Object.fromEntries(formData))
}
if (isSuccess) {
return (
You're subscribed!
)
}
return (
)
}
`
$3
`tsx
import { TownHallProvider } from '@townhall/react'
function App() {
return (
baseUrl="https://your-custom-domain.com"
timeout={15000}
>
)
}
`
$3
Full TypeScript support with typed responses:
`tsx
import { useTownHallForm, type TownHallResponse } from '@townhall/react'
function MyForm() {
const { submit, data } = useTownHallForm('form-id')
const handleSuccess = (response: TownHallResponse) => {
console.log('Submission ID:', response.id)
console.log('Auto-reply sent:', response.emails.autoReply.willSend)
}
const handleSubmit = async (formData: Record) => {
const response = await submit(formData)
if (response) {
handleSuccess(response)
}
}
// ...
}
`
API Reference
$3
React hook for form submissions.
Parameters:
| Parameter | Type | Description |
|-----------|------|-------------|
| formId | string | Your TownHall form ID |
| config.baseUrl | string | API base URL (default: https://townhall.gg) |
| config.timeout | number | Request timeout in ms (default: 30000) |
Returns:
| Property | Type | Description |
|----------|------|-------------|
| isSubmitting | boolean | True while submission is in progress |
| isSuccess | boolean | True after successful submission |
| error | TownHallError \| null | Error from last submission |
| data | TownHallResponse \| null | Response data on success |
| submit | (data) => Promise | Submit form data |
| reset | () => void | Reset form state |
| handleSubmit | (getData) => handler | Create form submit handler |
$3
Context provider for global configuration.
Props:
| Prop | Type | Description |
|------|------|-------------|
| baseUrl | string | API base URL |
| timeout | number | Request timeout |
| children | ReactNode | Child components |
Error Handling
`tsx
const { error } = useTownHallForm('form-id')
if (error) {
if (error.isRateLimited) {
return Too many submissions. Please wait a moment.
}
if (error.isFormInactive) {
return This form is no longer accepting submissions.
}
return Error: {error.message}
}
``