4.8 KiB
react-component-form
Manage React Forms with ease.
📜 About
react-component-form is a lightweight form component for React.js, it allows you to get the inputs values without state thanks to onChange
or onSubmit
props.
There is also a React Hooks to be used in combination with the <Form />
component to validate the data with Ajv JSON schema validator, see advanced usage.
Demo: https://divlo.github.io/react-component-form/.
💾 Install
npm install --save react-component-form
⚙️ Usage
Note : The examples use TypeScript, but obviously you can use JavaScript. Be aware that HandleForm
is the type definition for the onChange
and onSubmit
props.
import React from 'react'
import { Form } from 'react-component-form'
import type { HandleForm } from 'react-component-form'
export const Example = () => {
const handleSubmit: HandleForm = (formData, formElement) => {
console.log(formData) // { inputName: 'value of the input' }
formElement.reset()
}
return (
<Form onSubmit={handleSubmit}>
<input type='text' name='inputName' />
<button type='submit'>Submit</button>
</Form>
)
}
Basically you have access to the same props of the HTML form
tag in React, but the onSubmit and the onChange props are differents.
Instead to get the event
param you get formData
and formElement
parameters:
formData
: It's an object where the keys are the name of your inputs and the current value. Behind the scene, it uses the FormData constructor.formElement
: It's the actual HTML form element in the DOM so for example you can access the.reset()
method on a HTMLFormElement.
⚙️ Advanced Usage
This example shows how to use the <Form />
component with useForm
hook to validate the data with Ajv JSON schema validator.
You can see a more detailled example in the ./example folder.
import React from 'react'
import { Form, useForm } from 'react-component-form'
import type { HandleUseFormCallback } from 'react-component-form'
const schema = {
inputName: {
type: 'string',
minLength: 3,
maxLength: 20
}
}
export const Example = () => {
const { errors, handleUseForm } = useForm(schema)
const onSubmit: HandleUseFormCallback<typeof schema> = (
formData,
formElement
) => {
console.log(formData) // { inputName: 'value of the input validated' }
formElement.reset()
return null
}
return (
<Form onSubmit={handleUseForm(onSubmit)}>
<input type='text' name='inputName' />
{errors.inputName != null && <p>{errors.inputName[0].message}</p>}
<button type='submit'>Submit</button>
</Form>
)
}
💡 Contributing
Anyone can help to improve the project, submit a Feature Request, a bug report or even correct a simple spelling mistake.
The steps to contribute can be found in CONTRIBUTING.md.