57
52

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Reactで絞り込み機能付き検索を実装してみた

Last updated at Posted at 2018-06-02

Reactで絞り込み検索はどのように実装すればいいのだろうかと悩んだので、調べて実装してみました。

Demo

99e9830a636686dde28de71098a9903e.gif

javascriptで絞り込みを実装

Javascriptでは配列の要素を絞り込むためのfilterというメソットが用意されています。

filterメソッドは、配列の各要素に対してcallback関数を一回ずつ実行し、callback関数がtrueの時、その要素分だけ新たに配列を作成します。


let list = [1,2,3,4,5,6,7,8,9]
list.filter(item => item > 5); #[6, 7, 8, 9]

Reactで絞り込み機能を実装

ES6で実装しています

import React, { Component } from 'react';

class App extends Component {
  constructor() {
    super() 
    this.state = {
      initialItem: [
        "apple",
        "tree",
        "pen",
        "mike",
        "dog",
        "cat",
        "iphone",
        "book"
      ],
      items: []
    }
  }

  componentDidMount() {
    this.setState({items: this.state.initialItem})
  }

  filterList = (e) => {
    const updateList = this.state.initialItem.filter((item) => {
      return item.toLowerCase().search( e.target.value.toLowerCase()) !== -1;
    })
    this.setState({items: updateList})
  }

  render() {
    return (
      <div>
        <form action="">
          <input type="text" placeholder="search" onChange={this.filterList}/>
        </form>
        <div>
          {this.state.items.map((item, index) => {
            return (
              <li key={index}>{item}</li>
            )  
          })}
        </div>
      </div>
    );
  }
}

export default App;

こちらのGithubからclone可能です
https://github.com/yoshimoto8/searchFilter

参照

57
52
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
57
52

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?