Make uncontrolled select not set value on update
Ben Alpert committed
Jan 15, 2014 at 13:44 UTC
9c5c1ed90253b3d3f90d1d53b89d94fdba273b47
2 files changed
+29
-3
src/browser/dom/components/ReactDOMSelect.js
+12
-3
@@ -56,12 +56,17 @@ function selectValueType(props, propName, componentName) {
56
57
/**
58
* If `value` is supplied, updates <option> elements on mount and update.
59
+ * @param {boolean} force If true, updates the value even on an uncontrolled
60
+ * component.
61
* @private
62
*/
61
-function updateOptions() {
63
+function updateOptions(force) {
64
/*jshint validthis:true */
65
var multiple = this.props.multiple;
66
var propValue = LinkedValueUtils.getValue(this);
67
+ if (propValue == null && !force) {
68
+ return;
69
+ }
70
var value = propValue != null ? propValue : this.state.value;
71
var options = this.getDOMNode().options;
72
var selectedValue, i, l;
@@ -136,9 +141,13 @@ var ReactDOMSelect = ReactCompositeComponent.createClass({
141
return select(props, this.props.children);
142
},
143
139
- componentDidMount: updateOptions,
144
+ componentDidMount: function() {
145
+ updateOptions.call(this, true);
146
+ },
147
141
- componentDidUpdate: updateOptions,
148
+ componentDidUpdate: function() {
149
+ updateOptions.call(this, false);
150
+ },
151
152
_handleChange: function(event) {
153
var returnValue;
src/browser/dom/components/__tests__/ReactDOMSelect-test.js
+17
@@ -58,6 +58,23 @@ describe('ReactDOMSelect', function() {
58
expect(node.value).toEqual('giraffe');
59
});
60
61
+ it('should not control when using `defaultValue`', function() {
62
+ var stub =
63
+ <select defaultValue="giraffe">
64
+ <option value="monkey">A monkey!</option>
65
+ <option value="giraffe">A giraffe!</option>
66
+ <option value="gorilla">A gorilla!</option>
67
+ </select>;
68
+ var node = renderSelect(stub);
69
+
70
+ expect(node.value).toBe('giraffe');
71
+
72
+ node.value = 'monkey';
73
+ stub.forceUpdate();
74
+ // Uncontrolled selects shouldn't change the value after first mounting
75
+ expect(node.value).toEqual('monkey');
76
+ });
77
+
78
it('should allow setting `defaultValue` with multiple', function() {
79
var stub =
80
<select multiple={true} defaultValue={['giraffe', 'gorilla']}>