use-vmodel-react
v1.1.5
Published
A React hook that provides two-way binding similar to Vue's v-model, with customizable pre and post-processing of values.
Downloads
10
Maintainers
Readme
useVModel React Hook
useVModel
is a React hook that provides a simple way to implement two-way binding in your React components. It allows you to easily manage the state of an input field or any other value with customizable pre and post-processing.
Installation
npm install use-vmodel-react
Usage
import React from "react";
import useVModel from "use-vmodel-react";
function MyComponent() {
const email = useVModel("[email protected]");
return (
<div>
<label>Email:</label>
<input type="text" {...email.model} />
<p>Displayed Value: {email.displayValue}</p>
</div>
);
}
export default MyComponent;
API
useVModel(initialValue, {preProcess, postProcess, displayTransformer})
- initialValue: The initial value for the state.
- preProcess: A function to run before updating the state. Receives the current value and an
updateState
callback. ex. (value, update) => update(value.toUppercase()). (Default: Returns value) - postProcess: A function to run after updating the state. (Default: undefined)
- displayTransformer: A function to transform the displayed value. (Default: Returns value)
Example
const email = useVModel("[email protected]", {
preProcess: (val, callback) => {
console.log("preProcess", val);
if (val.includes("$")) {
return;
}
callback(val.toLowerCase());
},
postProcess: (val) => {
if (val.includes("!")) {
console.error("Invalid email");
}
},
displayTransformer: (val) => {
return val.toUpperCase() + "!";
},
});
Returns
An object with the following properties:
- model: An Object {value, onChange}
- displayValue: The transformed value returned by the displayTransformer