Skip to content

Instantly share code, notes, and snippets.

@jadeallencook
Last active December 23, 2018 11:36
Show Gist options
  • Save jadeallencook/678869f988bd65378d819496c4343e78 to your computer and use it in GitHub Desktop.
Save jadeallencook/678869f988bd65378d819496c4343e78 to your computer and use it in GitHub Desktop.
Easily sync your inputs to your state with this event handler.
import merge from 'lodash/merge';
export default function rjsBind(event) {
const path = event.target.getAttribute('data-path'),
paths = path.split('-'),
value = event.target.value;
let object = {};
paths.reduce(([object, value], path, idx) => {
object[path] = idx === paths.length - 1 ? value : {};
return [object[path], value];
}, [object, value]);
object = merge(this.state, object);
this.setState(() => object);
}
class MyComponent extends Component {
constructor() {
super();
this.state.foo.num = 0;
}
render() {
// input must have a 'data-path' that points to endpoint on state
return (
<input
type="number"
data-path="foo-num"
value={this.state.foo.num}
onChange={event => this.rjsBind.bind(this, event)()}
/>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment