Package Exports
- bknkit
- bknkit/styles.css
Readme
BKNKit
bknkit
is a powerful and flexible React library for building type-safe forms with ease. It leverages TypeScript to provide excellent autocompletion and error checking at development time, ensuring your forms are robust and maintainable.
This library provides a createTypeSafeForm
higher-order component that generates a suite of type-safe form field components tailored to your specific form data structure. It also includes context management for form state, validation, and submission handling.
Features
- Type-Safe by Design: Define your form values interface, and the library generates components that only accept valid field names and provide typed values.
- Comprehensive Field Types: Includes common input types, select, multi-select, async autocomplete, file uploads, and more.
- Built-in Validation: Comes with common validators (required, email, minLength) and allows for custom validation logic.
- Context-Based State Management: Simplifies form state handling across components.
- Easy to Integrate: Designed to be easily integrated into existing React projects.
- Customizable Styling: Components use Tailwind CSS classes internally and accept a
className
prop for easy customization. - Framework-Friendly: Works with Next.js, Astro, and other React-based frameworks with minimal configuration.
Installation
To install the library, use npm or yarn:
npm install bknkit
# or
yarn add bknkit
Make sure you have react
and react-dom
as peer dependencies in your project:
"peerDependencies": {
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
}
Styling
Important: bknkit
includes pre-compiled Tailwind CSS styles that you can import directly into your project:
// Import the pre-compiled CSS in your main component or entry file
import 'bknkit/styles.css';
This will ensure all Tailwind CSS classes used by the components are properly styled, without requiring any additional Tailwind configuration.
Astro Integration
When using bknkit
in Astro projects, simply import the pre-compiled CSS:
---
// In your Astro component or layout
import 'bknkit/styles.css';
import { YourFormComponent } from '../components/YourFormComponent';
---
<YourFormComponent client:load />
No additional Tailwind configuration is needed in your Astro project to use bknkit
.
Customizing Styles
All components in bknkit
accept a className
prop. You can use this prop to add your own Tailwind CSS classes (if your project uses Tailwind) or any other CSS classes to customize the appearance of the components. Your custom classes will be merged with or can override the default styles.
For example:
<Form.Text
label="Custom Styled Name"
name="name"
className="p-4 border-blue-500 rounded-lg" // Your custom classes
/>
If your project does not use Tailwind CSS, the components will render without the default Tailwind-based styling, and you will need to provide all styling yourself via the className
prop or other styling methods.
If your project uses Tailwind CSS with a custom configuration, the components will automatically adopt your project's Tailwind styling when you add your own classes.
Basic Usage
Define your form values interface:
interface MyFormValues { name: string; email: string; age?: number; }
Create a type-safe form instance:
import { createTypeSafeForm } from 'bknkit'; const Form = createTypeSafeForm<MyFormValues>();
Use the FormProvider and generated components:
import React, { useRef } from 'react'; import { FormProvider, required, email } from 'bknkit'; import type { FormContextType, FormValidators } from 'bknkit'; // Ensure your project has Tailwind CSS setup for bknkit styles to apply // Assume 'Form' is created as shown above const MyFormComponent: React.FC = () => { const formRef = useRef<FormContextType<MyFormValues>>(null); const initialValues: MyFormValues = { name: '', email: '' }; const validators: FormValidators<MyFormValues> = { name: [required('Name is required')], email: [required('Email is required'), email('Invalid email format')], }; const handleSubmit = (values: MyFormValues) => { console.log('Form submitted:', values); // Handle form submission (e.g., API call) }; return ( <FormProvider initialValues={initialValues} validators={validators} ref={formRef}> {(form) => ( <form onSubmit={form.handleSubmit(handleSubmit)}> <Form.Text label="Name" name="name" /> <Form.Email label="Email" name="email" /> {/* Add other Form fields as needed */} <button type="submit" className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"> Submit </button> </form> )} </FormProvider> ); }; export default MyFormComponent;
Available Form Fields
The createTypeSafeForm
function generates the following field components (used as Form.FieldName
):
Text
Email
Password
Select
Radio
Checkbox
Textarea
MultiSelect
AsyncAutocomplete
SearchableGroupedSelect
CreatableSelect
File
Each component accepts props like label
, name
(which is type-checked against your form values interface), placeholder
, and className
for custom styling.
Validation
The library includes helper functions for common validation rules:
required(message?: string)
email(message?: string)
minLength(length: number, message?: string)
isChecked(message?: string)
(for checkboxes)
Validators are passed to the FormProvider
.
TypeScript Support
bknkit
is built with TypeScript and exports complete type definitions. When you import from bknkit
, you'll automatically get proper TypeScript typings for all components, hooks, and utility functions.
// Import specific types when needed
import { FormContextType, FormValidators } from 'bknkit';
// Use with TypeScript generics
const formRef = useRef<FormContextType<MyFormValues>>(null);
// All validators are type-safe and will validate against your form structure
const validators: FormValidators<MyFormValues> = {
name: [required('Name is required')],
email: [required('Email is required'), email('Invalid email format')],
};
The package includes full declaration files (.d.ts) to provide excellent autocompletion and type-checking in your IDE.
Running the Demo
A demo page is included in the demo
directory of this project. To run it:
- Clone the repository (if you haven't already).
- Install dependencies:
npm install
- Build the library:
npm run build
- Build the demo:
npm run build:demo
- The demo's
index.html
uses a CDN for Tailwind for simplicity. In a real project usingbknkit
, you would need to have Tailwind CSS set up in that project. - Open
demo/index.html
in your browser or serve thedemo
directory.
Building the Library
To build the library for publishing:
npm run build
This will generate JavaScript files (ESM and CJS formats) and TypeScript declaration files in the dist
directory.
Scripts
npm run build
: Cleans and builds the library for production (JS, TS Decls).npm run build:js
: Builds the JavaScript (ESM and CJS) versions.npm run build:esm
: Builds the ES Module version.npm run build:cjs
: Builds the CommonJS version.npm run clean
: Removes thedist
anddemo/dist
directories.npm run lint
: Lints the codebase using ESLint (requires ESLint setup).npm run typecheck
: Checks for TypeScript errors.npm test
: (Placeholder) Runs tests.
Contributing
Contributions are welcome! Please refer to the repository's issue tracker and pull request guidelines. (The user should update this section with actual contribution guidelines and repository links).
License
This project is licensed under the MIT License. See the LICENSE file for details.