Last active
July 26, 2020 12:09
-
-
Save tungd/8367229 to your computer and use it in GitHub Desktop.
React LinkedState with path-based state access. Use case: http://stackoverflow.com/questions/21057219/react-js-2-way-bindings-two-levels-deep-path-in-valuelink/21058282#21058282
JSFiddle:
This file contains 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
/** | |
* react-catalyst.js | |
* | |
* LinkedState for Facebook's React UI Library. Add support for | |
* deep path state access. | |
* | |
* Author: Tung Dao <[email protected]> | |
* | |
* Usage: | |
* | |
* var WithLink = React.createClass({ | |
* mixins: [ReactCatalyst.LinkedStateMixin], | |
* getInitialState: function() { | |
* return { values: [{ text: 'Hello!' }] }; | |
* }, | |
* render: function() { | |
* return <input type="text" valueLink={this.linkState('values.0.text')} />; | |
* } | |
* }); | |
*/ | |
(function (root, factory) { | |
if (typeof define === 'function' && define.amd) { | |
define([], factory); | |
} else if (typeof exports === 'object') { | |
module.exports = factory(); | |
} else { | |
root.ReactCatalyst = factory(); | |
} | |
}(this, function () { | |
"use strict"; | |
function getIn(object, path) { | |
var stack = path.split('.'); | |
while (stack.length > 1) { | |
object = object[stack.shift()]; | |
} | |
return object[stack.shift()]; | |
} | |
function updateIn(object, path, value) { | |
var current = object, stack = path.split('.'); | |
while (stack.length > 1) { | |
current = current[stack.shift()]; | |
} | |
current[stack.shift()] = value; | |
return object; | |
} | |
function setPartialState(component, path, value) { | |
component.setState( | |
updateIn(component.state, path, value)); | |
} | |
return { | |
LinkedStateMixin: { | |
linkState: function(path) { | |
return { | |
value: getIn(this.state, path), | |
requestChange: setPartialState.bind(null, this, path) | |
} | |
} | |
} | |
} | |
})); |
Hey thanks for this. I've got a bunch of forms I've developing and this scratches an itch for me.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I included this here: https://github.com/tungd/react-catalyst, with tests and some other useful mixins.