Skip to content

Commit

Permalink
MultiSelect can be used as a controlled component (#156) (#160)
Browse files Browse the repository at this point in the history
  • Loading branch information
baptwaels authored and liorheber committed Jul 23, 2019
1 parent e763c1a commit 01e6017
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/components/multi_select_state.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,10 @@ const withMultiSelectState = WrappedComponent =>
componentWillReceiveProps(nextProps) {
const { searchValue, searchSelectedItemsValue } = this.props;
if (this.props.selectedItems !== nextProps.selectedItems) {
this.setState({ selectedItems: nextProps.selectedItems });
this.setState({
selectedItems: nextProps.selectedItems,
filteredSelectedItems: nextProps.selectedItems
});
}
if (this.props.items !== nextProps.items) {
const { items } = nextProps;
Expand Down Expand Up @@ -101,7 +104,6 @@ const withMultiSelectState = WrappedComponent =>
componentDidMount() {
window.addEventListener("keyup", this.onKeyUp);
}

componentWillUnmount() {
window.removeEventListener("keyup", this.onKeyUp, false);
}
Expand Down
46 changes: 46 additions & 0 deletions stories/multi-select.stories.js
Original file line number Diff line number Diff line change
Expand Up @@ -357,4 +357,50 @@ storiesOf("React Multi Select", module)
/>
);
})
)
.add(
"As a controlled component",
withReadme(Readme, () => {
class SelectedItemsController extends React.Component {
SINGLE_ITEM = [{ id: 1, label: "Item 1" }];
MULTI_ITEMS = [
{ id: 2, label: "Item 2" },
{ id: 4, label: "Item 4" }
]

constructor(props) {
super(props);
this.state = {
selectedItems: this.SINGLE_ITEM,
};
}

render() {
return (
<React.Fragment>
<input
style={{ marginBottom: "10px" }}
value="set Selected Items from outside"
type="button"
onClick={() => {
this.setState({
selectedItems: this.state.selectedItems.length > 1 ? this.SINGLE_ITEM : this.MULTI_ITEMS
});
}}
/>
<ReactMultiSelect
items={utils.items}
selectedItems={this.state.selectedItems}
loading={boolean("Loading", false)}
onChange={action("onChange")}
showSearch={boolean("Show search", true)}
showSelectAll={boolean("Show select all", true)}
/>
</React.Fragment>
);
}
}

return <SelectedItemsController />;
})
);

0 comments on commit 01e6017

Please sign in to comment.