Project For learner – React.js Auto complete Search Textresult in Browser with Bootstrap And Javascript Complete

Welcome Learner today in this blog post we will be Develop an auto-complete search text result in bootstrap and react.js. All the Complete source code of the application is shown Down.

In order to lets started, you need to make a file index.html and copy-paste the mentioned code

 

index.html  

 

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css"/>
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

 

And instantly create a style.css  file and copy-paste the next code

 

style.css

 

body {
  background-color: #2D91B3;
}
.input {
  margin-top: 50px;
  z-index: 1;
}
input {
  width: 100%;
  height: 40px;
  box-shadow: 0px 0px 6px 1px rgba(0, 0, 0, .6);
  border-radius: 10px;
  border: none;
  padding-left: 15px;
  outline: none;
  
}

.srchList {
  background-color: #6DB8D1;
  border-radius: 5px;
  padding-top: 10px;
  margin-top: -7px;
}

ul {
  list-style-type: decimal;
  color: #363636;
}

READ  React.js Auto complete idea Component exemplar in Browser Using Javascript

 

script.js

 

class App extends React.Component {
  constructor(props) {
    super(props);
    this.items = [
      "David",
      "Damien",
      "Sara",
      "James",
      "Jane",
      "Sapiens"
    ];
    
    this.state = {
      suggestions: [],
      text: ''
    }
  }
  
onTextChanged = (e) => {
  const value = e.target.value;
  let suggestions = [];
  if(value.length > 0) {
    const regex = new RegExp(`^${value}`, 'i');
    suggestions = this.items.sort().filter(v => regex.test(v));
  }
  this.setState(() => ({suggestions, text: value}));
}

suggestionSelected(value) {
  this.setState(() => ({
    text: value,
    suggestions: []
  }));
}

renderSuggestions() {
  const {suggestions} = this.state;
  if(suggestions.length === 0) {
    return null;
  }
  return (
    <div className="srchList">
      <ul>
        {suggestions.map((item) => <li onClick={() => this.suggestionSelected(item)}>{item}</li>)}
      </ul>
    </div>
  );
}

  render() {
    const { text } = this.state;
    return (
      <div className="container">
        <div className="row justify-content-md-center">
          <div className="col-md-12 input">
            <input value={text} onChange={this.onTextChanged} type="text" placeHolder="Search" />
          </div>
          <div className="col-md-12 justify-content-md-center">
            {this.renderSuggestions()}
          </div>
        </div>
      </div>
    );
  }
}
        
ReactDOM.render(<App />, document.getElementById('root'));

Leave a Comment

Your email address will not be published. Required fields are marked *