Moglobin's
article thumbnail

 

참고: 

medium.com/crobyer/search-filter-with-react-js-88986c644ed5

 

Search Filter with React js

React js can be very handy when it comes to the use of API and data storage. The response recorded from an API call can be used across the…

medium.com

 


우리가 웹에서 가장 많이 사용하는 기능 중 하나는 검색기능일 것이다.

 

React js는 API 요청 이후 지역 저장소 내에서 데이터베이스의 충돌을 막아줌으로써 검색의 과정을 쉽게 만들어준다. 

 

예제를 통해 React js 로 검색 기능을 만드는 방법에 대해 알아보자.

 

 

아래와 같이 임의의 사람의 이름과 나이, 국적을 담은 샘플 JSON 파일이 있다.

import react,{Component} from "react";

const Information = [
  {
    "name":"Samule",
    "age":21,
    "country":"USA"
  },
  {
    "name":"Sam",
    "age":21,
    "country":"USA"
  },
  {
    "name":"Mark",
    "age":21,
    "country":"Africa"
  },
  {
    "name":"Markus",
    "age":21,
    "country":"Africa"
  },
  {
    "name":"Aayush",
    "age":21,
    "country":"India"
  },
  {
    "name":"Sean",
    "age":21,
    "country":"Ireland"
  },
  {
    "name":"Eduardo",
    "age":21,
    "country":"France"
  },
  {
    "name":"Dustin",
    "age":21,
    "country":"Spain"
  },
  {
    "name":"Alexendra",
    "age":21,
    "country":"USA"
  },
  {
    "name":"Lee",
    "age":21,
    "country":"China"
  },
  {
    "name":"Jim",
    "age":21,
    "country":"Korea"
  }
];

export default Information;

 

이 JSON 파일을 화면으로 나타내게 하기 위해서는 우선 App.js에 해당 JSON 파일을 import 해야한다. 

 

import React, { Component } from 'react';

import './App.css';
import Information from './info-json';

class App extends Component {

  render(){
   }
}

export default App;

 

다음 단계는 JSON 파일의 배열 속 object의 요소들을 분석하여 분리 / 표현하는 것이다.

이를 위해 map function을 이용하고, 이것을 viewport에 디스플레이 하도록 한다. 

 

import React, { Component } from 'react';
import './App.css';
import Information from './info-json';

class App extends Component {

  render(){
    const styleInfo = {
      paddingRight:'10px'
    }
    const items = Information.map(data=>{
      return(
      <div>
        <ul>
          <li style={{position:'relative',left:'10vh'}}>
            <span style={styleInfo}>{data.name}</span>
            <span style={styleInfo}>{data.age}</span>
            <span style={styleInfo}>{data.country}</span>
          </li>
        </ul>
      </div>
      )
    })

    return item;
}

export default App;

 

이 시점에서 해당 코드를 브라우저를 통해 실행하면 다음과 같이 나타난다. 

 

Mapping the json file on to the screen

이제 검색 박스를 화면에 추가해보자.

 

import React, { Component } from 'react';
import './App.css';
import Information from './info-json';

class App extends Component {

  render(){
    const styleInfo = {
      paddingRight:'10px'
    }
    const elementStyle ={
      border:'solid',
      borderRadius:'10px',
      position:'relative',
      left:'10vh',
      height:'3vh',
      width:'20vh',
      marginTop:'5vh',
      marginBottom:'10vh'
    }
    const items = Information.map(data=>{
      return(
      <div>
        <ul>
          <li style={{position:'relative',left:'10vh'}}>
            <span style={styleInfo}>{data.name}</span>
            <span style={styleInfo}>{data.age}</span>
            <span style={styleInfo}>{data.country}</span>
          </li>
        </ul>
      </div>
      )
    })

    return (
      <div>
      <input type="text" placeholder="Enter item to be searched" style={elementStyle} onChange={(e)=>this.searchSpace(e)} />
      {items}
      </div>
    )
  }
}

export default App;

위의 코드를 실행하면 아래와 같이 나온다.

 

이제 가장 중요한 검색 기능 구현하기이다.

 

검색 기능이 실현되기 위해서는 map function과 함께 filter function을 추가해야한다. 하지만 이 전에 우리는 검색 박스 안의 내용이 변하는 것에 대응하기 위한 용도의 state를 정립한다.

 

  constructor(){
    super();

    this.state={
      search:null
    };
  }

 

맨 위에 해당 코드를 추가해준다. 

 

위의 작업으로 state는 초기 상태가 null로 설정된 search 라는 변수를 갖게 된다.

이제는 검색어에 따른 검색 결과를 나타내는 방법을 알아보자.

이를 위해서 우리는 검색 박스 안의 변화를 포착해내는 함수를 추가하고, 검색박스의 상태값을 state 변수로 설정해야한다.

 

import React, { Component } from 'react';
import './App.css';
import Information from './info-json';

class App extends Component {

  constructor(){
    super();

    this.state={
      search:null
    };
  }

  searchSpace=(event)=>{
    let keyword = event.target.value;
    this.setState({search:keyword})
  }

  render(){
    const styleInfo = {
      paddingRight:'10px'
    }
    const elementStyle ={
      border:'solid',
      borderRadius:'10px',
      position:'relative',
      left:'10vh',
      height:'3vh',
      width:'20vh',
      marginTop:'5vh',
      marginBottom:'10vh'
    }
    const items = Information.map(data=>{
      return(
      <div>
        <ul>
          <li style={{position:'relative',left:'10vh'}}>
            <span style={styleInfo}>{data.name}</span>
            <span style={styleInfo}>{data.age}</span>
            <span style={styleInfo}>{data.country}</span>
          </li>
        </ul>
      </div>
      )
    })

    return (
      <div>
      <input type="text" placeholder="Enter item to be searched" style={elementStyle} onChange={(e)=>this.searchSpace(e)} />
      {items}
      </div>
    )
  }
}

export default App;

 

마지막으로, 검색 변수에 따라 데이터가 분류되는 filter 함수를 if와 else if의 조건문을 통해 구현한다. 

 

import React, { Component } from 'react';
import './App.css';
import Information from './info-json';

class App extends Component {

  constructor(){
    super();

    this.state={
      search:null
    };
  }

  searchSpace=(event)=>{
    let keyword = event.target.value;
    this.setState({search:keyword})
  }

  render(){
    const styleInfo = {
      paddingRight:'10px'
    }
    const elementStyle ={
      border:'solid',
      borderRadius:'10px',
      position:'relative',
      left:'10vh',
      height:'3vh',
      width:'20vh',
      marginTop:'5vh',
      marginBottom:'10vh'
    }
    const items = Information.filter((data)=>{
      if(this.state.search == null)
          return data
      else if(data.name.toLowerCase().includes(this.state.search.toLowerCase()) || data.country.toLowerCase().includes(this.state.search.toLowerCase())){
          return data
      }
    }).map(data=>{
      return(
      <div>
        <ul>
          <li style={{position:'relative',left:'10vh'}}>
            <span style={styleInfo}>{data.name}</span>
            <span style={styleInfo}>{data.age}</span>
            <span style={styleInfo}>{data.country}</span>
          </li>
        </ul>
      </div>
      )
    })

    return (
      <div>
      <input type="text" placeholder="Enter item to be searched" style={elementStyle} onChange={(e)=>this.searchSpace(e)} />
      {items}
      </div>
    )
  }
}

export default App;

 

이제 검색 박스 안에 이름과 국적을 검색하면 우리가 찾는 조건의 데이터가 화면에 표시될 것이다. 

 

 


해변 검색을 위해 map 함수와 filter 함수를 사용하여 코드를 짜보았다. 

https://youtu.be/mZvKPtH9Fzo

위 영상을 주로 참고하였는데, 

 

여기서는 

 

{useState} 를 import 하여 아래와 같이 코드를 짜더라.

 

 

ko.reactjs.org/docs/hooks-state.html

 

Using the State Hook – React

A JavaScript library for building user interfaces

ko.reactjs.org

useState 에 대해서는 위 문서를 참고한다. 

 

 

function App() {
  const [searchTerm, setSearchTerm] = useState('')
  return (
  <div className="App">
    <input type="text" placeholder="Search..." onChange={event => {setSearchTerm(event.target.value)}}/>
    <div className="container">
    {JSONDATA.filter((val)=> {
      if (searchTerm == "")
      {return val}
      else if (val.sta_nm.toLowerCase().includes(searchTerm.toLowerCase()) || val.sido_nm.toLowerCase().includes(searchTerm.toLowerCase()))
      {return val}
    }).map((val, key)=> {
      return <div className="beaches" key={key}>
        <p>{val.sta_nm}</p>
        <img src={val.beach_img}/>
        </div>
    })}
    </div>
  </div>
  );
}

 

기존에 짰던 코드 말고 새로운 파일에 작성했는데 일단 기능만을 구현해보고 싶어서이다. 

 

아무것도 검색 안 한 상태.

 

 

css와 레이아웃을 좀 더 공부해야할 것 같다. 요소들이 정렬되는게 마음에 안드는데 바꾸는 데 어려움이 있다. 

profile

Moglobin's

@슈플로프

Take your time 🍋