React

by nimishgoel056

HTML

<html>

  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.35.3/es6-shim.min.js"></script>
  </head>

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

</html>

CSS

body {
  margin-top:20px;
  background-color: white;
  font-family: sans-serif;
}

#root {
  width: 500px;
  margin: 0 auto;
}

h1 {
  font-size: 20px;
  margin: 8px 0 16px;
  text-align: center;
}

.options {
  padding-left: 0;
  margin-top: 0px;
  list-style: none;
}

.options li {
    padding: 8px;
    border: 1px solid #ddd;
    cursor: pointer;
}

.options li:hover {
  background-color: #f5f5f5;
}

.auto-complete {
  padding: 8px;
  width: 100%;
}

.action-option {
  background-color: #ddd;
}

React

function getLabels(keyword) {
  const allLabels = ['NextActions', 'Someday_Actions', 'Costco', 'Alexa'];
  const result = allLabels
    .filter(function(x) {
      return x.toLowerCase().indexOf(keyword.toLowerCase()) > -1;
    });
  return result;
}


function getLabelsAsync(keyword) {
  const result = getLabels(keyword);
  const delay = Math.random() * 800 + 200; // delay 200~1000ms
  return new Promise(function(resolve, reject) {
    setTimeout(resolve, delay, result);
  });
}

class TextField extends React.Component {

	userInput = "";
  lastSelectedIndex = -1;
	constructor(props) {
  	super(props);
    this.state = {
    	labels: [],
      showDropDown: false,
      activeOption: 0,
    };
  }
  
  handleInputChange = (event) => {
  	const { name, value } = event.target;
    this.lastSelectedIndex = value.lastIndexOf("@");
    let results = [];
    let showDropDown = false;
    if(this.lastSelectedIndex > -1) {
    	const label = value.substring(this.lastSelectedIndex + 1);
      results = getLabels(label);
      showDropDown = true;
    }
    this.userInput = value;
    this.setState({
    	showDropDown,
    	results
    });
  }
  
  
  
  handleOptionSelect = (index) => {
  	const { activeOption, results, userInput } = this.state;
    this.userInput = this.userInput.substring(0, this.lastSelectedIndex) + results[index];
    this.lastSelectedIndex = -1;
    this.setState({
      activeOption: 0,
      showDropDown: false
    });
  }
  
  render() {
  	const { showDropDown, results, activeOption } = this.state;
    return ( 
      <div>
        
        <input value={this.userInput} name="userInput" className="auto-complete" type = "text" onChange={this.handleInputChange}/>
        {showDropDown && (
        	<ul className="options">
            {results.map((label, index) => {
            	let className;
              if (index === activeOption) {
                className = 'action-option';
              }
            	return <li key={index}...