1.1.5 • Published 1 month ago

use-vmodel-react v1.1.5

Weekly downloads
-
License
ISC
Repository
github
Last release
1 month ago

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("default@email.com");

	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("default@email.com", {
	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
1.1.5

1 month ago

1.1.4

1 month ago

1.1.3

5 months ago

1.1.2

5 months ago

1.1.1

5 months ago

1.1.0

5 months ago

1.0.1

5 months ago