Skip to content

Instantly share code, notes, and snippets.

View gaperton's full-sized avatar

Vlad Balin gaperton

View GitHub Profile
// Minimal working example demonstrating the two-way data binding with React Hook.
import { useLink } from 'valuelink'
import * as React from 'react'
export const MyCoolComponent = () => {
const name = useLink( '' );
return (
<input {...name.props} />
)
// Minimal working example demonstrating the two-way data binding with React Hook.
import React, { useState } from 'react'
export const MyCoolComponent = () => {
const [ name, setName ] = useState( '' );
return (
<input value={ name }
onChange={ e => setName( e.target.value ) }
/>
// Minimal working example demonstrating the two-way data binding with React Hook.
import { useLink } from 'valuelink'
import * as React from 'react'
// We don't want to deal with error markup in every input, do we?
const Input = ({ link, ...props }) => {
return (
<div>
<input {...link.props} {...props} />
<span>{ link.error || '' }</span>
import React from 'react';
import { useLink } from 'valuelink'
function Example() {
const users = useLink([]);
return (
<div>
{ users.map( ( user, i ) => (
<div key={i}>
@gaperton
gaperton / pickuser2.jsx
Last active May 17, 2019 04:37
PuckUser Component
function useLink( init ){
const [ value, set ] = useState( init );
// It can be a class with useful methods, like this one:
// https://github.com/VoliJS/NestedLink/blob/master/valuelink/src/link.ts
// But we just use the plain object here to illustrate an idea.
return { value, set };
}
const PickUser = ({ $selected /* link to some upper component state */ }) => {
// Declare the local component's state as a link.
@gaperton
gaperton / pickuser.jsx
Last active May 17, 2019 04:36
Show user
const userToString = x => x.name + ' <' + x.email + '>';
const PickUser = ({ user }) => (
<div>
  <input value={userToString(user)}/>
</div>
)
export const EditUser = ({ $selected, close }) => {
const $filter = useLink('');
return (
<>
<DelayedInput autoFocus
$value={ $filter }
placeholder="Start typing..."
onBlur={ close } />
export const DelayedInput = ({ $value, timeout = 1000, …props }) => {
 const $inputValue = useBoundLink( $value );
 // TODO: How to sync the state back?
 return <input {…$inputValue.props} {…props}/>;
}
export const DelayedInput = ({ $value, timeout = 1000, ...props }) => {
const $inputValue = useBoundLink( $value )
.onChange(
useThrottle(
x => $value.set( x ),
timeout,
[ $value.value ]
)
);