Auto Complete in React JS class

The autocomplete attribute specifies whether a form or an input field should have autocomplete on or off. Autocomplete allows the browser to predict the value. When a user starts to type in a field, the browser should display options to fill in the field, based on earlier typed values.

Suboor Khan
Suboor Khan

Suboor Khan

Software Engineer

React

Form.JSX

import React, { Component } from "react";
import AutoCompleteInput from "./AutoCompleteInput";


export default class AddTodo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: "",
      items: [],
    };
  }


  componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/todos")
      .then((response) => response.json())
      .then((json) => {
        const el = json.map((el) => el.title);
        this.setState({
          items: el,
        });
      });
  }


  render() {
    return (
      <>
        
          
          
        
      
    );
  }
}

AutoInput.js

  import React, { Component, Fragment } from "react";
import PropTypes from "prop-types";


class AutocompleteInput extends Component {
  static propTypes = {
    suggestions: PropTypes.instanceOf(Array)
  };


  static defaultProps = {
    suggestions: []
  };


  constructor(props) {
    super(props);


    this.state = {
      // The active selection's index
      activeSuggestion: 0,
      // The suggestions that match the user's input
      filteredSuggestions: [],
      // Whether or not the suggestion list is shown
      showSuggestions: false,
      // What the user has entered
      userInput: "",


      userSelection: ""
    };
  }


  onChange = e => {
    const { suggestions } = this.props;
    const userInput = e.currentTarget.value;


    // Filter our suggestions that don't contain the user's input
    const filteredSuggestions = suggestions.filter(
      suggestion =>
        suggestion.toLowerCase().indexOf(userInput.toLowerCase()) > -1
    );


    this.setState({
      activeSuggestion: 0,
      filteredSuggestions,
      showSuggestions: true,
      userInput: e.currentTarget.value
    });
  };


  onClick = e => {
      console.log("e.currentTarget")
    this.setState({
      activeSuggestion: 0,
      filteredSuggestions: [],
      showSuggestions: false,
      userInput: e.currentTarget.innerText,
      userSelection: e.currentTarget.innerText
    });
  };


  onKeyDown = e => {
    const { activeSuggestion, filteredSuggestions } = this.state;


    // User pressed the enter key
    if (e.keyCode === 13) {
      this.setState({
        activeSuggestion: 0,
        showSuggestions: false,
        userInput: filteredSuggestions[activeSuggestion],
        userSelection: filteredSuggestions[activeSuggestion]
      });
    }
    // User pressed the up arrow
    else if (e.keyCode === 38) {
      if (activeSuggestion === 0) {
        return;
      }


      this.setState({ activeSuggestion: activeSuggestion - 1 });
    }
    // User pressed the down arrow
    else if (e.keyCode === 40) {
      if (activeSuggestion - 1 === filteredSuggestions.length) {
        return;
      }


      this.setState({ activeSuggestion: activeSuggestion + 1 });
    }
  };


  onBlur = e => {
    if (this.state.userSelection === "") {
    //   this.setState({
    //     activeSuggestion: 0,
    //     filteredSuggestions: [],
    //     showSuggestions: false,
    //     userInput: '',


    //   });
    }
  };


  render() {
    const {
      onChange,
      onClick,
      onKeyDown,
      onBlur,
      state: {
        activeSuggestion,
        filteredSuggestions,
        showSuggestions,
        userInput
      }
    } = this;


    let suggestionsListComponent;


    if (showSuggestions && userInput) {
      if (filteredSuggestions.length) {
        suggestionsListComponent = (
          
    {filteredSuggestions.map((suggestion, index) => { let className; // Flag the active suggestion with a class if (index === activeSuggestion) { className = "suggestion-active"; } return (
    &lt;form&gt; &lt;AutoCompleteInput suggestions={this.state.items} required={true} /&gt; &lt;input type=&quot;submit&quot; value=&quot;submit&quot; /&gt; &lt;/form&gt;
    ); })}
); } else { suggestionsListComponent = (
No suggestions, you're on your own!
); } } return ( &lt;Fragment&gt; &lt;input type=&quot;text&quot; onChange={onChange} onKeyDown={onKeyDown} value={userInput} onBlur={onBlur} required={this.props.required} /&gt; {suggestionsListComponent} &lt;/Fragment&gt; ); } } export default AutocompleteInput;
HomeNews feedsWorkSessionsContact