Responsive two-way binding between components
npm install --save use-bind
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>
);
};
};
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>
);
}
MIT © zhengjiaqi
This hook is created using create-react-hook.