use-bind
v1.0.1
Published
Responsive two-way binding between components.
Downloads
36
Maintainers
Readme
use-bind
Responsive two-way binding between components
Install
npm install --save use-bind
Usage
import * as React from 'react';
import useBind from 'use-bind';
const useBindExample = () => {
const myBind = useBind(true);
const onClick = useCallback(() => {
myBind.value = myBind.value + 1
}, [myBind])
return (
<div>
<p onClick={onClick}>
Click me and value will increment to {myBind.value} .
</p>
</div>
);
};
};
Examples
Using it between components
Source code - ParentComponentExample.tsx
// ParentComponentExample.tsx
const ParentComponent: React.FC<IParentComponent> = (props: IParentComponent) => {
const myBind = useBind(1);
const onClick = useCallback(() => {
myBind.value += 10;
}, [myBind]);
return (
<div>
<div className="parent-componment-value-click" onClick={onClick}>
<span>Click me</span> will increase the value of the child component by 10 each time.
</div>
<ChildComponent myBind={myBind}></ChildComponent>
</div>
);
}
Source code - ChildComponentExample.tsx
// ChildComponentExample.tsx
interface IChildComponent {
myBind: IBind<number>
}
const ChildComponent: React.FC<IChildComponent> = ({ myBind }: IChildComponent) => {
const onClick = useCallback(() => {
myBind.value += 1;
}, [myBind]);
return (
<div>
<div className="child-componment-value-click" onClick={onClick}>
<span>Click me</span> will increase the value of the child component itself by 1 each time.
</div>
<div className="child-componment-value">
Child Component Value: <span>{myBind.value}</span>
</div>
</div>
);
}
License
MIT © zhengjiaqi
This hook is created using create-react-hook.