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.
🚀 Recent Updates - Field Consolidation
v0.2.0: We've consolidated 5 redundant select field components into a single UnifiedSelectField
for better maintainability and performance:
- 60% smaller bundle size (~20KB → ~8KB for select components)
- Unified API across all select field types
- Backward compatible - existing code continues to work
- New capabilities - combinations of features previously impossible
Migration: Most users don't need to change anything. The old field names (SelectField
, MultiSelectField
, etc.) still work through wrapper components. See MIGRATION_NOTICE.md
for details.
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.
- Unified Select Component: All select variants (basic, multi, grouped, creatable, async) unified into one extensible component.
- 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.
- Standalone Form Fields: All form components can be used independently outside of FormContext with their state managed directly through props.
- 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.
- Flexible Installation: Can be used as a package dependency or as a starter kit by copying components directly into your project.
Installation
To install the library, use npm or yarn:
npm install bknkit
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"
}
Using as a Starter Pack
BKNKit can be used like shadcn/ui as a starter pack for your form components:
Option 1: Copy components directly
You can copy individual components from the src
folder directly into your project:
- Navigate to the GitHub repository
- Browse to the
src
directory
- Copy the needed component files (e.g.,
Text.tsx
, Select.tsx
) into your project
- Import and use them directly in your application
This approach gives you full control to modify the components as needed for your specific project requirements.
Option 2: Use as a package
As described in the Installation section, you can install BKNKit as a package dependency:
npm install bknkit
Then import and use the components as needed:
import { createTypeSafeForm } from '@bknkit/form';
const Form = createTypeSafeForm<YourFormType>();
This approach is ideal when you want to maintain the ability to update the library while using it across multiple projects.
Styling
Important: bknkit
includes pre-compiled Tailwind CSS styles that you can import directly into your project:
import '@bknkit/form/styles.css';
This will ensure all Tailwind CSS classes used by the components are properly styled, without requiring any additional Tailwind configuration.
Tailwind CSS 4 Integration
For projects using Tailwind CSS 4, you'll need to use the @source
directive to import BKNKit styles. Add the following to your global CSS file:
@import "tailwindcss";
@import "tw-animate-css";
@source "../../node_modules/@bknkit/form";
If you're using a different package name or folder structure, adjust the path accordingly:
@source "../../node_modules/@bknkit/form";
@source "node_modules/@bknkit/form";
This configuration ensures Tailwind CSS 4 correctly processes all the BKNKit styles during build.
Astro Integration
When using bknkit
in Astro projects, simply import the pre-compiled CSS:
---
// In your Astro component or layout
import '@bknkit/form/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"
/>
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/form';
const Form = createTypeSafeForm<MyFormValues>();
-
Use the FormProvider and generated components:
import React, { useRef } from 'react';
import { FormProvider, required, email } from '@bknkit/form';
import type { FormContextType, FormValidators } from '@bknkit/form';
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);
};
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
NIK
NIP
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 { FormContextType, FormValidators } from '@bknkit/form';
const formRef = useRef<FormContextType<MyFormValues>>(null);
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 using bknkit
, you would need to have Tailwind CSS set up in that project.
- Open
demo/index.html
in your browser or serve the demo
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 the dist
and demo/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.
Perintah:
- npx @tailwindcss/upgrade --force