Last active
December 23, 2018 11:36
-
-
Save jadeallencook/678869f988bd65378d819496c4343e78 to your computer and use it in GitHub Desktop.
Easily sync your inputs to your state with this event handler.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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