Skip to content

Commit 01e6017

Browse files
baptwaelsliorheber
authored andcommitted
MultiSelect can be used as a controlled component (#156) (#160)
1 parent e763c1a commit 01e6017

File tree

2 files changed

+50
-2
lines changed

2 files changed

+50
-2
lines changed

src/components/multi_select_state.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,10 @@ const withMultiSelectState = WrappedComponent =>
4949
componentWillReceiveProps(nextProps) {
5050
const { searchValue, searchSelectedItemsValue } = this.props;
5151
if (this.props.selectedItems !== nextProps.selectedItems) {
52-
this.setState({ selectedItems: nextProps.selectedItems });
52+
this.setState({
53+
selectedItems: nextProps.selectedItems,
54+
filteredSelectedItems: nextProps.selectedItems
55+
});
5356
}
5457
if (this.props.items !== nextProps.items) {
5558
const { items } = nextProps;
@@ -101,7 +104,6 @@ const withMultiSelectState = WrappedComponent =>
101104
componentDidMount() {
102105
window.addEventListener("keyup", this.onKeyUp);
103106
}
104-
105107
componentWillUnmount() {
106108
window.removeEventListener("keyup", this.onKeyUp, false);
107109
}

stories/multi-select.stories.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -357,4 +357,50 @@ storiesOf("React Multi Select", module)
357357
/>
358358
);
359359
})
360+
)
361+
.add(
362+
"As a controlled component",
363+
withReadme(Readme, () => {
364+
class SelectedItemsController extends React.Component {
365+
SINGLE_ITEM = [{ id: 1, label: "Item 1" }];
366+
MULTI_ITEMS = [
367+
{ id: 2, label: "Item 2" },
368+
{ id: 4, label: "Item 4" }
369+
]
370+
371+
constructor(props) {
372+
super(props);
373+
this.state = {
374+
selectedItems: this.SINGLE_ITEM,
375+
};
376+
}
377+
378+
render() {
379+
return (
380+
<React.Fragment>
381+
<input
382+
style={{ marginBottom: "10px" }}
383+
value="set Selected Items from outside"
384+
type="button"
385+
onClick={() => {
386+
this.setState({
387+
selectedItems: this.state.selectedItems.length > 1 ? this.SINGLE_ITEM : this.MULTI_ITEMS
388+
});
389+
}}
390+
/>
391+
<ReactMultiSelect
392+
items={utils.items}
393+
selectedItems={this.state.selectedItems}
394+
loading={boolean("Loading", false)}
395+
onChange={action("onChange")}
396+
showSearch={boolean("Show search", true)}
397+
showSelectAll={boolean("Show select all", true)}
398+
/>
399+
</React.Fragment>
400+
);
401+
}
402+
}
403+
404+
return <SelectedItemsController />;
405+
})
360406
);

0 commit comments

Comments
 (0)