리액트 예제 - 연락처 보기, 검색기능

노요셉·2019년 11월 18일
0

react시작하기

목록 보기
2/5

소스코드 - https://github.com/leaveittogod0123/ReactLab/tree/master/Contact

Contact 기본 구조

-src
	-component
		-App.jsx
		-Contact.jsx
		-ContactInfo.jsx
        
    -index.html
    -index.jsx

연락처 보기

간단하게 div태그에 name과 phone 넘버를 넣어 화면에 렌더링할 컴포넌트 ContactInfo를 만듭니다.

검색기능

연락처 데이터를 state로 관리하는 Contact 컴포넌트가 있습니다.
input 태그를 만들어서 입력한 값에 해당하는 name의 연락처만 보이게 할 검색기능을 구현합니다.

현재 데이터는

contactData: [
        {
          name: "Abet",
          phone: "010-0000-0001",
        },
        {
          name: "Betty",
          phone: "010-0000-0001",
        },
        {
          name: "Charie",
          phone: "010-0000-0001",
        },
      ]

위와 같은 형태입니다.

간단하게 render하기 전에 미리 데이터를 정렬하고
필터링하여 검색한 값에 해당하는 연락처만 보이게 합니다.

데이터가 저장되어있는 자료구조는 배열입니다. 자바스크립트 array.prototype.sort()를 통해 정렬할 수 있습니다. unicode를 기반으로 정렬합니다. ?? 나오시는 분들은 여기에 자세한 내용을 정리해놨으니 참고해주시면 됩니다.

for문을 돌면서 배열에 저장되어있는 연락처와 input 태그의 값과 일일히 비교합니다.
자바스크립트에는 그 일에 딱 맞는 메서드가 있습니다. array.protoype.filter( 콜백 )
콜백에서는 boolean 타입을 리턴합니다. true를 리턴한 값만 저장된 새로운 배열을 리턴합니다.

문자열을 비교하고싶은데요. string.prototype.indexOf()를 통해 문자열을 비교합니다.

대소문자를 구분하지 않고 검색하길 원합니다. string.prototype.toLowerCase() 를 통해 비교할 값을 소문자로 바꿔버립니다.

예제하면서 맞닥뜨린 에러

tslint type validation

Type Validation

컴포넌트 에서 원하는 props 의 Type 과 전달 된 props 의 Type 이 일치하지 않을 때 콘솔에서 오류 메시지가 나타나게 하고 싶을 땐, 컴포넌트 클래스의 propTypes 객체를 설정하면 됩니다. 또한, 이를 통하여 필수 props 를 지정할 수 있습니다. 즉, props 를 지정하지 않으면 콘솔에 오류 메시지가 나타납니다.

sth is missing in props validation

터미널을 열고

yarn add prop-types
import PropTypes from "prop-types";

...

ContactInfo.propTypes = {
  contact: PropTypes.shape({
    name: PropTypes.string,
    phone: PropTypes.string,
  }),
};

props값을 임의로 지정해주지 않았을 때 사용할 기본값을 설정하는 방법

has no corresponding defaultProps declaration

ContactInfo.defaultProps = {
  contact: {},
};

Catalina로 업그레이드 한 후에 에러가 발생했어요.

xcrun: error: invalid active developer path

xcode-select --install

레퍼런스: macOs - OS 업데이트 후 git 등 오류 발생 시 솔루션 - http://redutan.github.io/


airbnb의 lint규칙을 따르는데요. 제가 따르고 싶지 않은 경우는

eslint("이 문자열을 클립보드에 저장합니다.")

저는 .eslintrc를 따로 안 만들고, package.json에 넣었습니다.

package.json

...
  ,
  "eslintConfig": {
    "extends": [
      "airbnb",
      "prettier"
    ],
    "rules": {
      "react/prefer-stateless-function": 0,
      "react/jsx-filename-extension": 0,
      "react/jsx-one-expression-per-line": 0,
      "react/destructuring-assignment": 0
    },
    "env": {
      "browser": true
    }
  }

prettier설정에
arrow function에 (파라미터) 괄호 넣기
https://prettier.io/docs/en/options.html


package.json

...
  ,
  "eslintConfig": {
    "parser": "babel-eslint", <- 추가합니다.
    "extends": [
      "airbnb",
      "prettier"
    ],
    "rules": {
      "react/prefer-stateless-function": 0,
      "react/jsx-filename-extension": 0,
      "react/jsx-one-expression-per-line": 0,
      "react/destructuring-assignment": 0,
      "react/no-array-index-key": 0 <- 추가한 설정입니다.
    },
    "env": {
      "browser": true
    }
  }

value 값이 0이면 해당 rule을 꺼버리는거고요.
1로 한다면 경고가 뜨게 됩니다. 이렇게 설정을 덮어씌울 수 있습니다.

레퍼런스: "Parsing error: unexpected token ="
레퍼런스: babel-eslint

profile
서로 아는 것들을 공유해요~

0개의 댓글