React.js ライブラリ「react-autosuggest」を使用してサジェスト機能を実装する

React.js ライブラリ「react-autosuggest」を使用してサジェスト機能を実装する

ライブラリ「react-autosuggest」をインストールすると、サジェスト機能が簡単に可能です。ここでは、3つキーワードのみの実装ですが、react.jsで react-autosuggestを利用するための手順と簡単な使い方を記述してます。

環境

  • OS  CentOS Linux release 8.0.1905 (Core)
  • node V12.13.1
  • npm 6.14.1
  • React 16.13.0

react.js環境構築

下記のコマンドで構築してます。ここでは、react-appという名前でプロジェクトを作成してます。

create-react-app react-app

react-autosuggestインストール

作成したプロジェクトに移動して、インストールします。

## 作成したプロジェクトに移動
cd react-app
 
## インストール
npm install react-autosuggest

react-autosuggest 使い方

srcディレクトリにsample.jsと名前で下記のコードを記述します。

import React from 'react';
import Autosuggest from 'react-autosuggest';

const languages = [
  {
    name: 'java',
    year: 1972
  },
  {
    name: 'C言語',
    year: 2012
  },
  {
    name: 'fotran',
    year: 2012
  }
];

const getSuggestions = value => {
  const inputValue = value.trim().toLowerCase();
  const inputLength = inputValue.length;

  return inputLength === 0 ? [] : languages.filter(lang =>
    lang.name.toLowerCase().slice(0, inputLength) === inputValue
  );
};

const getSuggestionValue = suggestion => suggestion.name;

// Use your imagination to render suggestions.
const renderSuggestion = suggestion => (
  <div>
    {suggestion.name}{suggestion.year}
  </div>
);

class Sample extends React.Component {
  constructor() {
    super();
    this.state = {
      value: '',
      suggestions: []
    };
  }

  onChange = (event, { newValue }) => {
    this.setState({
      value: newValue
    });
  };

  onSuggestionsFetchRequested = ({ value }) => {
    this.setState({
      suggestions: getSuggestions(value)
    });
  };

  onSuggestionsClearRequested = () => {
    this.setState({
      suggestions: []
    });
  };

  render() {
    const { value, suggestions } = this.state;

    const inputProps = {
      placeholder: 'プログラム言語を入力して下さい',
      value,
      onChange: this.onChange
    };

    // Finally, render it!
    return (
      <Autosuggest
        suggestions={suggestions}
        onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
        onSuggestionsClearRequested={this.onSuggestionsClearRequested}
        getSuggestionValue={getSuggestionValue}
        renderSuggestion={renderSuggestion}
        inputProps={inputProps}
      />
    );
  }
}

export default Sample

次に、srcディレクトリ配下にあるApp.jsを下記のように編集します。

import React from 'react';
import Sample from './sample';
import './App.css';

function App() {
  const style = {
    width: "50%",
    margin: "0 auto",
    marginTop: 150
  };
  return (
    <div className="App">
      <div style={style}>
        <Sample />
      </div>
    </div>
  );
}

export default App;

実行します。

npm start

ブラウザから http://プライベートIP:3000にアクセスすると、サジェスト機能が3ワードだけですが、実装されていることが確認できます。