From 64e286b9b8e188b068553be7f899b8bea4a22df5 Mon Sep 17 00:00:00 2001 From: Sly Bridges Date: Mon, 23 Nov 2015 16:20:11 +0100 Subject: [PATCH] Add clearableValue option --- README.md | 8 ++++++++ src/Select.js | 3 ++- test/Select-test.js | 25 ++++++++++++++++++++++++- 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 33e32e03e1..23b2a901a1 100644 --- a/README.md +++ b/README.md @@ -89,6 +89,14 @@ You can enable multi-value selection by setting `multi={true}`. In this mode: * The `onChange` event provides an array of the selected options as the second argument * The first argument to `onChange` is always a string, regardless of whether the values of the selected options are numbers or strings * By default, only options in the `options` array can be selected. Setting `allowCreate` to true allows new options to be created if they do not already exist. +* By default, selected options can be cleared. To disable the possibility of clearing a particular option, add `clearableValue: false` to that option: +```javascript +var options = [ + { value: 'one', label: 'One' }, + { value: 'two', label: 'Two', clearableValue: false } +]; +``` +Note: the `clearable` prop of the Select component should also be set to `false` to prevent allowing clearing all fields at once ### Async options diff --git a/src/Select.js b/src/Select.js index 076a0b6cf2..70da3c04a6 100644 --- a/src/Select.js +++ b/src/Select.js @@ -348,6 +348,7 @@ const Select = React.createClass({ popValue () { var valueArray = this.getValueArray(); if (!valueArray.length) return; + if (valueArray[valueArray.length-1].clearableValue === false) return; this.setValue(valueArray.slice(0, valueArray.length - 1)); }, @@ -449,7 +450,7 @@ const Select = React.createClass({ return valueArray.map((value, i) => { return ( { options = [ { value: 'one', label: 'One' }, - { value: 'two', label: 'Two' }, + { value: 'two', label: 'Two', clearableValue: false }, { value: 'three', label: 'Three' }, { value: 'four', label: 'Four' } ]; @@ -1660,6 +1660,29 @@ describe('Select', () => { ]); }); + it('doesn\'t show the X if clearableValue=false', () => { + + setValueProp(['two']); + onChange.reset(); // Ignore previous onChange calls + + var twoDeleteButton = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value-icon')[0]; + + expect(twoDeleteButton, 'to be', undefined); + }); + + it('doesn\'t allow clearing with backspace if clearableValue=false on the latest element', () => { + + setValueProp(['four', 'two']); + onChange.reset(); // Ignore previous onChange calls + + pressBackspace(); + expect(onChange, 'was not called'); + var items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value-label'); + expect(items[0], 'to have text', 'Four'); + expect(items[1], 'to have text', 'Two'); + + }); + describe('with late options', () => { beforeEach(() => {