JavaScript
prop-type 팩키지 정리 - PropTypes
폴리프레임
2024. 11. 28. 07:42
반응형
React에서는 부모 컴포넌트가 자식 컴포넌트에 데이터를 전달할 때 props를 사용합니다. 이때 prop-types는 props가 예상된 데이터 타입과 일치하는지 확인하는 데 도움을 줍니다. 즉, prop-types 패키지는 React 컴포넌트의 props 타입을 검증하기 위해 사용됩니다. TypeScript를 사용하지 않는 React 프로젝트에서 유용합니다. 아래 명령으로 별도의 설치가 필요합니다.
npm install --save prop-types
사용예제 - 일반
import React from 'react';
import PropTypes from 'prop-types';
const MyComponent = ({ name, age, isActive }) => (
<div>
<h1>{name}</h1>
<p>Age: {age}</p>
<p>Status: {isActive ? 'Active' : 'Inactive'}</p>
</div>
);
MyComponent.propTypes = {
name: PropTypes.string.isRequired, // 필수 문자열
age: PropTypes.number, // 숫자 타입
isActive: PropTypes.bool // 불리언 타입
};
MyComponent.defaultProps = {
age: 0, // 기본값 설정
isActive: false
};
export default MyComponent;
- propTypes: 각 prop의 타입을 정의합니다.
- isRequired: 해당 prop이 반드시 필요함을 나타냅니다.
- defaultProps: props가 전달되지 않았을 때의 기본값을 설정합니다.
지원되는 PropTypes의 주요 타입
- PropTypes.string
- PropTypes.number
- PropTypes.bool
- PropTypes.array
- PropTypes.object
- PropTypes.func
- PropTypes.node (렌더링 가능한 모든 것)
- PropTypes.element (React 요소)
- PropTypes.oneOf(['값1', '값2']) (특정 값 중 하나)
- PropTypes.shape({ key: PropTypes.type }) (객체의 구조 검증)
사용 예제 - PropTypes.node
import React from 'react';
import PropTypes from 'prop-types';
const NodeExample = ({ children }) => (
<div>
<h2>Node Example:</h2>
<div>{children}</div>
</div>
);
NodeExample.propTypes = {
children: PropTypes.node.isRequired // 렌더링 가능한 모든 것 허용
};
export default NodeExample;
<NodeExample>
<p>This is a paragraph.</p>
<span>Span text</span>
{'Some plain text'}
</NodeExample>
사용 예제 - PropTypes.element
const ElementExample = ({ childElement }) => (
<div>
<h2>Element Example:</h2>
{childElement}
</div>
);
ElementExample.propTypes = {
childElement: PropTypes.element.isRequired // 단일 React 요소만 허용
};
export default ElementExample;
<ElementExample childElement={<button>Click me</button>} />
// 아래는 에러
<ElementExample childElement="Just a string" />
사용 예제 - PropTypes.oneOf([...])
const OneOfExample = ({ status }) => (
<div>
<h2>Status:</h2>
<p>{status}</p>
</div>
);
OneOfExample.propTypes = {
status: PropTypes.oneOf(['active', 'inactive', 'pending']).isRequired // 제한된 값 하나만 허용
};
export default OneOfExample;
<OneOfExample status="active" />
// 아래 코드는 허용된 것이 아니므로 에러
<OneOfExample status="completed" />
사용 예제 - PropTypes.shape({...})
// 객체의 구조를 설명 할때
const ShapeExample = ({ user }) => (
<div>
<h2>User Info:</h2>
<p>Name: {user.name}</p>
<p>Age: {user.age}</p>
<p>Email: {user.email}</p>
</div>
);
ShapeExample.propTypes = {
user: PropTypes.shape({
name: PropTypes.string.isRequired, // 필수 문자열
age: PropTypes.number, // 선택 숫자
email: PropTypes.string // 선택 문자열
}).isRequired // 전체 객체가 필수
};
export default ShapeExample;
<ShapeExample user={{ name: 'Alice', age: 30, email: 'alice@example.com' }} />