Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

HTML

            
              <div id="root"></div>
            
          
!

CSS

            
              /* superficial styling */

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.app {
  padding: 1rem;
  color: var(--col-primary-text);
}

.grey {
  padding: 1rem;
  background: #ccc;
  margin-top: 6.6rem;
}

body {
  font-family: "Helvetica", sans-serif;
}

/* /end superficial styling */

:root {
  --col-primary-active: #08f;
  --col-primary-text: #4c4c4c;
  --col-separator: #cccccc;
}

.drop-down__list-item {
  padding-left: 5px;
  height: 30px;
  display: flex;
  align-items: center;
}

.drop-down__list-item > input {
  margin: 0.3rem;
}

.new-drop-down__button {
    color: inherit;
    position: relative;
    border: 1px solid var(--col-separator);
    border-radius: 3px;
    width: var(--width-list);
    font-size: 12px;
    height: 30px;
    text-align: left;
    padding-left: 5px;
    cursor: pointer;
    font-family: inherit;
}

.drop-down-icon {
  position: absolute;
  width: 30px;
  height: 29px;
  display: flex;
  align-items: center;
  justify-content: center;
  top: 0;
  right: 0;
}

.new-drop-down {
  --font-size: 12px;
  --width-list: 135px;
}

.new-drop-down {
  font-size: var(--font-size);
  width: var(--width-list);
  position: relative;
  z-index: 1;
}

button.new-drop-down__button.new-drop-down--is-open {
    color: var(--col-primary-active);
}

button.new-drop-down__button.new-drop-down--is-open span {
    color: var(--col-primary-text);
}

.new-drop-down__list-wrapper {
  border: 1px solid var(--col-separator);
  max-width: var(--width-list);
  width: 100%;
  background: white;
  position: absolute;
}



            
          
!

JS

            
              console.clear();

function debounce(fn, delay) {
  let timer;
  const thisContext = this;
  const args = arguments;
  return function() {
    clearTimeout(timer);
    timer = setTimeout(() => {
      return fn.apply(thisContext, args);
    }, delay);
  };
}

class DropDownListItem extends React.Component {
  constructor(props) {
    super(props);
    this.debouncedToggleChangeListItem = debounce(
      this.toggleChangeListItem,
      150
    );
  }
  toggleChangeListItem = () => {
    const { listData, uniqueKey } = this.props;
    this.props.toggleChangeListItem(listData[uniqueKey]);
  };
  onKeyUp = e => {
    if (e.keyCode === 13) {
      const { listData, uniqueKey } = this.props;
      this.props.toggleChangeListItem(listData[uniqueKey]);
    }
  };
  render() {
    const { listData, isChecked } = this.props;
    const id = `${listData.label}__${listData.value}`;
    return (
      <div
        tabIndex={0}
        className="drop-down__list-item"
        onClick={this.debouncedToggleChangeListItem}
        onKeyUp={this.onKeyUp}
      >
        <input
          tabIndex={-1}
          id={id}
          type="checkbox"
          checked={isChecked}
          value={listData.value}
        />
        <label htmlFor={id}>{listData.label}</label>
      </div>
    );
  }
}

/**********************************/
// propTypes
/**********************************/
// DropDownListItem.propTypes = {
//     listData: PropTypes.object,
//     uniqueKey: PropTypes.string,
//     toggleChangeListItem: PropTypes.func,
//     isChecked: PropTypes.bool
// };

class NewDropDown extends React.Component {
  state = {
    isOpen: false
  };
  toggleIsOpen = () => {
    this.setState({
      isOpen: !this.state.isOpen
    });
  };
  // handle click outside ~ to close the dropdown
  componentWillMount() {
    document.addEventListener("mousedown", this.handleDocClick, false);
  }
  componentWillUnmount() {
    document.removeEventListener("mousedown", this.handleDocClick, false);
  }
  handleDocClick = e => {
    if (!this.wrapper.contains(e.target)) {
      this.setState({
        isOpen: false
      });
    }
  };
  renderDropDownIcon = () => {
    if (this.props.customRenderDropDownIcon) {
      return this.props.customRenderDropDownIcon();
    } else {
      return <span className="drop-down-icon">▼</span>;
    }
  };
  renderSelected = () => {
    const { isOpen } = this.state;
    const { selected, data, uniqueKey } = this.props;
    let labelContent = "";
    if (!selected.length) {
      labelContent = "None Selected";
    } else if (selected.length === data.length) {
      labelContent = "All Selected";
    } else if (selected.length === 1) {
      const selectedOne = data.find(item => item[uniqueKey] === selected[0]);
      labelContent = selectedOne.label;
    } else {
      labelContent = `${selected.length} Selected`;
    }
    const activeClass = isOpen ? "new-drop-down--is-open" : "";
    return (
      <button
        className={`new-drop-down__button ${activeClass}`}
        onClick={this.toggleIsOpen}
      >
        <span>{labelContent}</span>
        {this.renderDropDownIcon()}
      </button>
    );
  };
  renderDropDownList = () => {
    const {
      data,
      toggleChangeListItem,
      uniqueKey,
      selected,
      shouldHaveSelectAll
    } = this.props;

    let data_ = [...data];

    if (shouldHaveSelectAll) {
      data_ = [{ label: "Select All", value: "ALL" }, ...data];
    }

    const getIsChecked = ({ listData, uniqueKey, selected }) => {
      let isChecked = false;
      if (listData[uniqueKey] === "ALL") {
        if (selected.length === data.length) {
          isChecked = true;
        } else {
          isChecked = false;
        }
      } else {
        isChecked = selected.indexOf(listData[uniqueKey]) > -1;
      }
      return isChecked;
    };

    return data_.map((listData, index) => {
      const isChecked = getIsChecked({ listData, uniqueKey, selected });
      return (
        <DropDownListItem
          key={index}
          toggleChangeListItem={toggleChangeListItem}
          listData={listData}
          uniqueKey={uniqueKey}
          isChecked={isChecked}
        />
      );
    });
  };
  render() {
    return (
      <div className="new-drop-down" ref={wrapper => (this.wrapper = wrapper)}>
        {this.renderSelected()}
        {this.state.isOpen && (
          <div className="new-drop-down__list-wrapper">
            {this.renderDropDownList()}
          </div>
        )}
      </div>
    );
  }
}

/**********************************/
// propTypes
/**********************************/
// NewDropDown.propTypes = {
//     isMultiSelect: PropTypes.bool,  
//     shouldHaveSelectAll: PropTypes.bool,
//     selected: PropTypes.array,
//     data: PropTypes.array,
//     uniqueKey: PropTypes.string,
//     toggleChangeListItem: PropTypes.func,
//     customRenderDropDownIcon: () => null
// };

class App extends React.Component {
  state = {
    uniqueKey: "value",
    selected: [],
    data: [
      {
        label: "One",
        value: 1
      },
      {
        label: "Two",
        value: 2
      },
      {
        label: "Three",
        value: 3
      }
    ]
  };
  toggleChangeListItem = uniqueKey => {
    if (uniqueKey === "ALL") {
      if (this.state.selected.length === this.state.data.length) {
        this.setState({
          selected: []
        });
      } else {
        const allUniqueKeys = this.state.data.map(
          item => item[this.state.uniqueKey]
        );
        this.setState({
          selected: allUniqueKeys
        });
      }
    } else {
      let updatedSelected = [...this.state.selected];
      if (updatedSelected.indexOf(uniqueKey) > -1) {
        updatedSelected.splice(updatedSelected.indexOf(uniqueKey), 1);
      } else {
        updatedSelected.push(uniqueKey);
      }
      this.setState({
        selected: updatedSelected
      });
    }
  };
  renderSelected = () => {
    const { selected, data, uniqueKey } = this.state;
    const data_ = data.slice();
    let res = [];
    for (let i = 0; i < selected.length; i++) {
      for (let j = 0; j < data_.length; j++) {
        if (data_[j][uniqueKey] === selected[i]) {
          res.push(data_[j]);
          data_.splice(j, 1);
        }
      }
    }
    return JSON.stringify(res);
  };
  render() {
    return (
      <div className="app">
        <h3>Custom multi-select dropdown react</h3>
        <br />
        <NewDropDown
          shouldHaveSelectAll={true}
          uniqueKey={this.state.uniqueKey}
          data={this.state.data}
          selected={this.state.selected}
          toggleChangeListItem={this.toggleChangeListItem}
        />
        <div className="grey">
          <h5>Selected:</h5>
          {this.renderSelected()}
        </div>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));

            
          
!
999px

Console