├── .github
└── workflows
│ └── release.yml
├── .gitignore
├── .npmignore
├── LICENSE.md
├── README.md
├── package-lock.json
├── package.json
├── src
├── index.ts
├── types.ts
├── useForm.ts
└── utils.ts
└── tsconfig.json
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | name: 🚀 formbold react release
2 |
3 | on:
4 | push:
5 | branches:
6 | - main # Adjust this to your desired branch
7 |
8 | jobs:
9 | publish:
10 | name: 🚀 formbold react release
11 | runs-on: ubuntu-latest
12 |
13 | steps:
14 | - name: Checkout code
15 | uses: actions/checkout@v2
16 |
17 | - name: Setup Node.js
18 | uses: actions/setup-node@v2
19 | with:
20 | node-version: 18
21 | registry-url: "https://registry.npmjs.org"
22 |
23 | - name: Clear npm cache
24 | run: npm cache clean --force
25 | - name: Delete node_modules
26 | run: rm -rf node_modules
27 |
28 | - name: Install dependencies
29 | run: npm ci
30 |
31 | - name: Build
32 | run: npm run build # Replace with your build command if needed
33 |
34 | - name: Publish to npm
35 | run: npm publish --access public
36 | env:
37 | NODE_AUTH_TOKEN: ${{ secrets.NPM_AUTH_TOKEN_FORMBOLDREACT }}
38 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | /dist
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | src
3 |
4 | tsconfig.json
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 Lineicons
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6 |
7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8 |
9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | # Formbold-react — The easiest way to configure and use Form in React/Next.js
3 | React package for [FormBold](https://formbold.com/) which simplifies the integration of FormBold with React/Next.js projects.
4 |
5 | FormBold is a multipurpose form API and serverless backend solution compatible with all hosting, SSG, and frameworks. It allows you to receive form submissions directly in your email, slack, telegram, notion, and more. It's ready for use with any Static, Jamstack, and SSG sites, such as HTML, React, Next.js, Gatsby, Vue, Nuxt, Hugo, and Jekyll.
6 |
7 | It offers a wide range of form fields, advanced features like conditional logic, and seamless integration with other tools.
8 |
9 | ## Installation
10 |
11 | ```bash
12 | npm install formbold-react
13 | ```
14 |
15 | or
16 |
17 | ```bash
18 | yarn add formbold-react
19 | ```
20 |
21 | ## Usages
22 |
23 | To use it you have to import it in your Form component. Then call it with the form_id.
24 |
25 | And at the end, attach the handleSubmit function to the onSubmit event.
26 |
27 | ```typescript
28 | import { useForm } from "formbold-react";
29 |
30 | function Form() {
31 | const [state, handleSubmit] = useForm("form_id");
32 |
33 | if (state.succeeded) {
34 | return
Form submitted successfully
;
35 | }
36 |
37 | return (
38 | <>
39 | Home Page
40 |
50 | >
51 | );
52 | }
53 |
54 | export default Form;
55 | ```
56 |
57 | ## Required fields
58 |
59 | To make certain fields mandatory in your form, you can use the `requiredFields` option when using the `useForm` hook. In the example below, the `email` field is set as a required field:
60 |
61 | ```typescript
62 | const [state, handleSubmit] = useForm("form_id", { requiredFields: ["email"] });
63 | ```
64 | This ensures that the form cannot be submitted unless the `email` field is filled out by the user.
65 |
66 |
67 | ## Custom error messages
68 | You can customize the error messages displayed when certain fields are not filled out in your form. By using the `errorMessages` option in the `useForm` hook, you can provide custom error messages for different scenarios.
69 |
70 | Here's an example of how you can set custom error messages for the `name` and `email` fields:
71 |
72 | ```typescript
73 | const [state, handleSubmit] = useForm("form_id", {
74 | requiredFields: ["name", "email"],
75 | errorMessages: {
76 | empty: "Please fill the form!",
77 | required: fields => `Please fill the required fields: ${fields.join(", ")}`,
78 | }
79 | });
80 | ```
81 |
82 | Feel free to customize the error messages according to your specific requirements.
83 |
84 |
85 | ## ****Useful Links and Information****
86 |
87 | For more information visit the [documentation](https://formbold.com/docs).
88 |
--------------------------------------------------------------------------------
/package-lock.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "formbold-react",
3 | "version": "1.1.1",
4 | "lockfileVersion": 3,
5 | "requires": true,
6 | "packages": {
7 | "": {
8 | "name": "formbold-react",
9 | "version": "1.1.1",
10 | "license": "MIT",
11 | "devDependencies": {
12 | "@types/react-dom": "19.0.0",
13 | "typescript": "5.8.2"
14 | },
15 | "peerDependencies": {
16 | "@types/react": "19.0.0",
17 | "react": "19.0.0",
18 | "react-dom": "19.0.0"
19 | }
20 | },
21 | "node_modules/@types/react": {
22 | "version": "19.0.0",
23 | "resolved": "https://registry.npmjs.org/@types/react/-/react-19.0.0.tgz",
24 | "integrity": "sha512-MY3oPudxvMYyesqs/kW1Bh8y9VqSmf+tzqw3ae8a9DZW68pUe3zAdHeI1jc6iAysuRdACnVknHP8AhwD4/dxtg==",
25 | "dependencies": {
26 | "csstype": "^3.0.2"
27 | }
28 | },
29 | "node_modules/@types/react-dom": {
30 | "version": "19.0.0",
31 | "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.0.0.tgz",
32 | "integrity": "sha512-1KfiQKsH1o00p9m5ag12axHQSb3FOU9H20UTrujVSkNhuCrRHiQWFqgEnTNK5ZNfnzZv8UWrnXVqCmCF9fgY3w==",
33 | "dev": true,
34 | "dependencies": {
35 | "@types/react": "*"
36 | }
37 | },
38 | "node_modules/csstype": {
39 | "version": "3.1.2",
40 | "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.2.tgz",
41 | "integrity": "sha512-I7K1Uu0MBPzaFKg4nI5Q7Vs2t+3gWWW648spaF+Rg7pI9ds18Ugn+lvg4SHczUdKlHI5LWBXyqfS8+DufyBsgQ=="
42 | },
43 | "node_modules/react": {
44 | "version": "19.0.0",
45 | "resolved": "https://registry.npmjs.org/react/-/react-19.0.0.tgz",
46 | "integrity": "sha512-V8AVnmPIICiWpGfm6GLzCR/W5FXLchHop40W4nXBmdlEceh16rCN8O8LNWm5bh5XUX91fh7KpA+W0TgMKmgTpQ==",
47 | "peer": true,
48 | "engines": {
49 | "node": ">=0.10.0"
50 | }
51 | },
52 | "node_modules/react-dom": {
53 | "version": "19.0.0",
54 | "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.0.0.tgz",
55 | "integrity": "sha512-4GV5sHFG0e/0AD4X+ySy6UJd3jVl1iNsNHdpad0qhABJ11twS3TTBnseqsKurKcsNqCEFeGL3uLpVChpIO3QfQ==",
56 | "peer": true,
57 | "dependencies": {
58 | "scheduler": "^0.25.0"
59 | },
60 | "peerDependencies": {
61 | "react": "^19.0.0"
62 | }
63 | },
64 | "node_modules/scheduler": {
65 | "version": "0.25.0",
66 | "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.25.0.tgz",
67 | "integrity": "sha512-xFVuu11jh+xcO7JOAGJNOXld8/TcEHK/4CituBUeUb5hqxJLj9YuemAEuvm9gQ/+pgXYfbQuqAkiYu+u7YEsNA==",
68 | "peer": true
69 | },
70 | "node_modules/typescript": {
71 | "version": "5.8.2",
72 | "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.2.tgz",
73 | "integrity": "sha512-aJn6wq13/afZp/jT9QZmwEjDqqvSGp1VT5GVg+f/t6/oVyrgXM6BY1h9BRh/O5p3PlUPAe+WuiEZOmb/49RqoQ==",
74 | "dev": true,
75 | "bin": {
76 | "tsc": "bin/tsc",
77 | "tsserver": "bin/tsserver"
78 | },
79 | "engines": {
80 | "node": ">=14.17"
81 | }
82 | }
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "formbold-react",
3 | "version": "1.1.1",
4 | "description": "Formbold package for react.",
5 | "main": "dist/index.js",
6 | "types": "./dist/index.ts",
7 | "exports": {
8 | "types": "./dist/index.d.ts",
9 | "default": "./dist/index.js"
10 | },
11 | "repository": {
12 | "type": "git",
13 | "url": "git+https://github.com/FormBold/formbold-react"
14 | },
15 | "author": "Formbold Team (https://formbold.com/)",
16 | "homepage": "https://formbold.com/",
17 | "scripts": {
18 | "build": "tsc --declaration"
19 | },
20 | "license": "MIT",
21 | "keywords": [
22 | "forms",
23 | "form",
24 | "form-api",
25 | "web-form",
26 | "react-form",
27 | "react",
28 | "formbold"
29 | ],
30 | "devDependencies": {
31 | "@types/react-dom": "^19.0.0",
32 | "typescript": "^5.8.2"
33 | },
34 | "peerDependencies": {
35 | "@types/react": "^19.0.0",
36 | "react": "^19.0.0",
37 | "react-dom": "^19.0.0"
38 | },
39 | "bugs": {
40 | "url": "https://github.com/FormBold/formbold-react/issues"
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------
1 | export { useForm } from "./useForm";
2 |
--------------------------------------------------------------------------------
/src/types.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * Error state for the useForm hook.
3 | */
4 | export type ErrorState = {
5 | /** The error message */
6 | message: string;
7 | /** The error status */
8 | status: boolean;
9 | };
10 |
11 | /**
12 | * Error messages for the useForm hook.
13 | */
14 | export type ErrorMessages = {
15 | /** Error message when the form is empty */
16 | empty?: string;
17 | /** Error message when the required fields are empty */
18 | required?: (fields: string[]) => string;
19 | };
20 |
21 | /**
22 | * Configuration options for the useForm hook.
23 | */
24 | export type Config = {
25 | /**
26 | * Custom error messages
27 | *
28 | * @example
29 | * errorMessages: {
30 | * empty: 'Oops the form is empty!',
31 | * required: fields => `You missed: ${fields.join(', ')}`,
32 | * }
33 | */
34 | errorMessages?: ErrorMessages;
35 | /**
36 | * List of required fields (by name) that must be filled before submitting the form.
37 | * @default []
38 | *
39 | * @example
40 | * requiredFields: ['name', 'email']
41 | */
42 | requiredFields?: string[];
43 | };
44 |
45 | export type DeepRequired = Required<{
46 | [K in keyof T]: T[K] extends Required ? T[K] : DeepRequired;
47 | }>;
48 |
49 | export type CaptchaRef = { current: { getValue: () => any } };
50 |
--------------------------------------------------------------------------------
/src/useForm.ts:
--------------------------------------------------------------------------------
1 | import { useState } from 'react';
2 | import { CaptchaRef, Config, DeepRequired, ErrorState } from './types';
3 | import { mergeConfig } from './utils';
4 |
5 | const defaultConfig: DeepRequired = {
6 | errorMessages: {
7 | empty: 'Please fill the form!',
8 | required: fields => `Please fill the required fields: ${fields.join(', ')}`,
9 | },
10 | requiredFields: [],
11 | };
12 |
13 | const defaultErrorState: ErrorState = {
14 | message: '',
15 | status: false,
16 | };
17 |
18 | const FORM_BOLD_SUBMISSION_API = 'https://formbold.com/s';
19 |
20 | /**
21 | * FormBold useForm hook
22 | * @param formId - The form ID
23 | * @param config - Configuration options
24 | * @returns An array containing the form state and the submit handler
25 | */
26 | const useForm = (formId: string, config?: Config) => {
27 | const { requiredFields, errorMessages } = mergeConfig(defaultConfig, config);
28 | const [error, setError] = useState(defaultErrorState);
29 | const [succeeded, setSucceeded] = useState(false);
30 | const [submitting, setSubmitting] = useState(false);
31 |
32 | const handleSubmit = (e: React.FormEvent, recaptchaRef?: CaptchaRef) => {
33 | e.preventDefault();
34 |
35 | // Getting the Form data
36 | const data = new FormData(e.currentTarget);
37 | //@ts-ignore
38 | const value = Object.fromEntries(data.entries());
39 | const finalData = { ...value };
40 |
41 | // Conditionally add "g-recaptcha-response" if recaptchaRef is provided
42 | if (recaptchaRef) {
43 | finalData['g-recaptcha-response'] = recaptchaRef.current.getValue();
44 | }
45 |
46 | //check if the values is empty
47 | //@ts-ignore
48 | const isEmpty = !Object.values(value).some(x => x !== null && x !== '');
49 | if (isEmpty) {
50 | return setError({
51 | message: errorMessages.empty,
52 | status: true,
53 | });
54 | }
55 |
56 | // Check if the required fields are empty
57 | const requiredFieldsEmpty = requiredFields.filter(field => !value[field]);
58 |
59 | if (requiredFieldsEmpty.length > 0) {
60 | return setError({
61 | message: errorMessages.required(requiredFieldsEmpty),
62 | status: true,
63 | });
64 | }
65 |
66 | setSubmitting(true);
67 |
68 | // submit the form
69 | fetch(`${FORM_BOLD_SUBMISSION_API}/${formId}`, {
70 | method: 'POST',
71 | headers: {
72 | 'Content-Type': 'application/json',
73 | },
74 | body: JSON.stringify(finalData),
75 | })
76 | .then(() => {
77 | setSucceeded(true);
78 | setError(defaultErrorState);
79 | })
80 | .catch(error => {
81 | setError({
82 | message: error.message,
83 | status: true,
84 | });
85 | setSucceeded(false);
86 | })
87 | .finally(() => {
88 | setSubmitting(false);
89 | });
90 | };
91 |
92 | return [{ error, succeeded, submitting }, handleSubmit] as const;
93 | };
94 |
95 | export { useForm };
96 |
97 |
--------------------------------------------------------------------------------
/src/utils.ts:
--------------------------------------------------------------------------------
1 | import { Config, DeepRequired } from './types';
2 |
3 | /**
4 | * Merges the provided configuration object with the default configuration,
5 | * overriding any properties that are specified in the provided object.
6 | *
7 | * @param config - The configuration object to merge with the default configuration.
8 | * @returns The merged configuration object.
9 | */
10 | export const mergeConfig = (defaultConfig: DeepRequired, config: Config = {}) => {
11 | const errorMessages = { ...defaultConfig.errorMessages, ...(config.errorMessages ?? {}) };
12 | return { ...defaultConfig, ...config, errorMessages }
13 | };
14 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "module": "commonjs",
5 | "lib": ["es6", "dom", "es2018.promise"],
6 | "jsx": "react",
7 | "strict": true,
8 | "esModuleInterop": true,
9 | "skipLibCheck": true,
10 | "forceConsistentCasingInFileNames": true,
11 | "outDir": "./dist"
12 | },
13 | "include": ["src"],
14 | "exclude": ["node_modules", "**/__tests__/*"]
15 | }
16 |
17 |
--------------------------------------------------------------------------------