React.js ライブラリ「downshift」を使用してオートコンプリート機能を実装する

ライブラリ「downshift」をインストールすると、オートコンプリート機能の実装が可能です。ここでは、react.jsで downshift を利用するための手順と簡単な使い方を記述してます。
環境
- OS CentOS Linux release 8.0.1905 (Core)
- node V12.13.1
- npm 6.14.2
- React 16.13.0
react.js環境構築
下記のコマンドで構築してます。ここでは、react-appという名前でプロジェクトを作成してます。
create-react-app react-app
downshiftインストール
作成したプロジェクトに移動して、インストールします。
## 作成したプロジェクトに移動
cd react-app
## インストール
npm install downshift
downshift使い方
srcディレクトリにsample.jsと名前で下記のコードを記述します。
import React from 'react';
import Downshift from 'downshift';
export const Sample = () => {
const items = [
{value: 'apple'},
{value: 'pear'},
{value: 'orange'},
{value: 'grape'},
{value: 'banana'},
]
return (
<Downshift
onChange={selection =>
alert(selection ? `You selected ${selection.value}` : 'Selection Cleared')
}
itemToString={item => (item ? item.value : '')}
>
{({
getInputProps,
getItemProps,
getLabelProps,
getMenuProps,
isOpen,
inputValue,
highlightedIndex,
selectedItem,
getRootProps,
}) => (
<div>
<label {...getLabelProps()}>Enter a fruit</label>
<div
style={{display: 'inline-block'}}
{...getRootProps({}, {suppressRefError: true})}
>
<input {...getInputProps()} />
</div>
<ul {...getMenuProps()}>
{isOpen
? items
.filter(item => !inputValue || item.value.includes(inputValue))
.map((item, index) => (
<li
{...getItemProps({
key: item.value,
index,
item,
style: {
backgroundColor:
highlightedIndex === index ? 'lightgray' : 'white',
fontWeight: selectedItem === item ? 'bold' : 'normal',
},
})}
>
{item.value}
</li>
))
: null}
</ul>
</div>
)}
</Downshift>
)
}
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にアクセスすると、オートコンプリート機能 が実装されていることが確認できます。

-
前の記事
dockerを使用して「owncloud」を構築する 2020.04.11
-
次の記事
CentOs7 ApacheのDocumentRoot(ドキュメントルート)をコマンドで確認する方法 2020.04.12
コメントを書く