0%

210311_TIL(React 기초)

오늘 배운 것

Snippet

https://snippet-generator.app/

설정 → 사용자 코드조각 → html 등 언어 설정 → json 형식으로 붙여넣기

React

컴포넌트 네이밍 컨벤션

1
HTML <button type="button" class="button">HTML 버튼 요소</button>
1
2
React Component (JSX)
<Button>React 버튼 요소</Button>

TitleCase 문법 사용을 권장

React ver 17

React 17 버전부터는 함수 컴포넌트에 대해 import React를 할 필요가 없다. 다만 class 컴포넌트에 대해서는class UploadButton extends React.Component 와 같은 경우를 위해 import React해야한다.

SVG Format

SVG는 코드로 이루어진 이미지 디자인 포멧이다. 디자인 포멧이지만 XML과 유사한 코드로 이뤄져있다. 그렇기 때문에 서버 통신에서 가장 큰 용량 중 하나를 차지하는 이미지 파일에 대한 사용을 줄이고 재사용이 가능해진다.

타입 검사

JS 타입 검사

1
2
3
4
5
6
7
// 데이터 타입 검사 유틸리티 함수
function validType(dataType, typeString) {
return (
Object.prototype.toString.call(dataType).slice(8, -1).toLowerCase() ===
typeString
);
}

Object.prototype.toString.call(dataType) 를 사용하면 정확한 타입을 알 수 있다. (Array, function, null 등이 object로 출력되는 type of 보다 직관적이다.

React 타입 검사

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// 타입 검사를 위한 객체
const PropTypes = {
string(props, propName, componentName) {
const value = props[propName];
const valueType = typeof value;
const expectedType = "string";

if (valueType !== expectedType) {
const errorMessage = `${componentName} 컴포넌트에 전달 된 ${propName}
${expectedType} 데이터 유형이 전달되어야 하나,
실제 전달된 속성 값 데이터 유형은 ${valueType}입니다. 확인해주세요.`;

return new Error(errorMessage);
}
},
};

/* -------------------------------------------------------------------------- */

export default function SVGIcon({ src, alt, className, ...restProps }) {
return (
<img
src={`${src}.svg`}
alt={alt}
className={`icon ${className}`.trim()}
{...restProps}
/>
);
}

SVGIcon.defaultProps = {
className: "",
};

// React 컴포넌트는 React에 의해
// 전달 속성(props)의 타입을 검사할 수 있는
// propTypes 속성을 제공합니다.
SVGIcon.propTypes = {
src: PropTypes.string,
// alt(){}
};

하지만 이미 React에서 제공하는 타입 검사 prop-types가 있다.

prop-types

npm i -D prop-types 로 설치할 수 있다.

1
2
3
4
5
6
import { string, number, bool } from "prop-types";

SVGIcon.propTypes = {
src: string.isRequired, //필수
alt: string,
};

Nyong’s GitHub