Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

bootstrap dropdown with state

import React from 'react';
import './style.css';
import ReactDOM from 'react-dom';
import $ from 'jquery';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isDropdownOpen: false,
      inputValue: '',
      options: ['action', 'newAction', 'oldAction']
    };
  }

  componentDidUpdate(prevProps, prevState) {
    if (
      $('.dropdown-menu')
        .attr('class')
        .indexOf('show') >= 0
    ) {
      $('#dropdownMenuButton').trigger('click.bs.dropdown');
      $('#dropdownMenuButton').trigger('click.bs.dropdown');
    } else {
      $('#dropdownMenuButton').trigger('click.bs.dropdown');
    }

    $('#search').focus();
  }

  handleChange = evt => {
    const value = evt.target.value;
    this.setState({ inputValue: value });
  };
  render() {
    return (
      <div>
        <h1>Hello StackBlitz!</h1>
        <h1>Hello StackBlitz!</h1>
        <h1>Hello StackBlitz!</h1>
        <h1>Hello StackBlitz!</h1>
        <h1>Hello StackBlitz!</h1>
        <h1>Hello StackBlitz!</h1>
        <div className="dropdown" ref={node => (this.DDRef = node)}>
          <button
            className="btn btn-secondary dropdown-toggle"
            type="button"
            id="dropdownMenuButton"
            data-toggle="dropdown"
            aria-haspopup="true"
            aria-expanded="false"
            onClick={() =>
              this.setState({ isDropdownOpen: !this.state.isDropdownOpen })
            }
          >
            {this.state.isDropdownOpen ? (
              <div style={{ display: 'flex' }}>
                <input
                  id="search"
                  type="text"
                  defaultValue={''}
                  value={this.state.inputValue}
                  placeholder={'Search'}
                  ref={node => (this.inputRef = node)}
                  onChange={this.handleChange}
                />
                <span
                  className="cancel-icon"
                  ref={node => (this.cancelRef = node)}
                >
                  x
                </span>
              </div>
            ) : (
              <div>Dropdown button</div>
            )}
          </button>
          <div className="dropdown-menu" aria-labelledby="dropdownMenuButton">
            {this.state.options
              .filter(el => el.startsWith(this.state.inputValue))
              .map(option => {
                return (
                  <a className="dropdown-item" href="#">
                    {option}
                  </a>
                );
              })}
          </div>
        </div>
      </div>
    );
  }
}

export default App;
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #bootstrap #dropdown #state
ADD COMMENT
Topic
Name
9+5 =