[React] Props

Props

Props는 컴포넌트 내부의 Immutable Data(변화하지 않는 데이터)를 처리할 때 사용된다.

JSX내부에 { this.props.propsName }이 있을 때, 컴포넌트를 렌더링할 때 propsName = "value"이런 식으로 전달하면 된다. 아래의 예제를 보자.

index.js

1
2
3
4
5
import React from 'react';
import ReactDOM from 'react-dom';
import PropsTest from './PropsTest';

ReactDOM.render(<PropsTest name="jessie" />, document.getElementById('root'));

index.js파일의 PropsTest확장 태그에 name="jessie" 애트리뷰트를 추가했다.

PropsTest.js

1
2
3
4
5
6
7
8
9
10
11
12
import React from 'react';

export default class PropsTest extends React.Component {
render() {
return (
<div>
<h1>Hello { this.props.name }</h1>
</div>

);
}
}

PropsTest확장 태그를 구현한 PropsTest클래스에서 애트리뷰트 값을 사용하기 위한 표현식은 { this.props.[애트리뷰트이름] }이다.

index.js파일에서 name이라는 애트리뷰트를 추가했기 때문에 PropsTest.js파일에서 { this.props.name }이라고 작성하면 된다.

실행결과


this.props.children

this.props.childeren은 기본적으로 갖고있는 props로써, 별도의 props이름 설정 없이 값을 설정할 수 있다. 아래의 예시를 보자.

index.js

1
2
3
4
5
import React from 'react';
import ReactDOM from 'react-dom';
import PropsTest from './PropsTest';

ReactDOM.render(<PropsTest name="jessie">I love React!!!</PropsTest>, document.getElementById('root'));

index.js파일의 PropsTest확장 태그 사이에 별도의 애트리뷰트 이름 없이 I love React!!!라는 문구를 작성했다.

PropsTest.js

1
2
3
4
5
6
7
8
9
10
11
12
13
import React from 'react';

export default class PropsTest extends React.Component {
render() {
return (
<div>
<h1>Hello { this.props.name }</h1>
<h2>{ this.props.children }</h2>
</div>

);
}
}

애트리뷰트 값을 사용하기 위한 표현식은 { this.props.children }이다.

실행결과


defaultProps - props 기본값 설정

컴포넌트 설정이 끝난 후, defaultProps객체를 설정하면 된다. 아래의 예제는 name props의 기본값을 ellie로 설정하고 있다.

index.js

1
2
3
4
5
import React from 'react';
import ReactDOM from 'react-dom';
import PropsTest from './PropsTest';

ReactDOM.render(<PropsTest>I love React!!!</PropsTest>, document.getElementById('root'));

index.js파일의 PropsTest확장 태그에 추가했던 name="jessie"애트리뷰트를 삭제했다. 따라서 현재 설정된 name애트리뷰트는 없다.

PropsTest.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import React from 'react';

export default class PropsTest extends React.Component {
render() {
return (
<div>
<h1>Hello { this.props.name }</h1>
<h2>{ this.props.children }</h2>
</div>

);
}
}

PropsTest.defaultProps = {
name: 'ellie'
};

PropsTest.js파일에서 defaultProps객체를 설정해주었다. name props의 기본값을 ellie로 설정했다. 이렇게 되면, index.js파일에서 별도의 애트리뷰트를 설정하지 않았을 때 기본값으로 nameellie가 들어가는 것이다.

실행결과


PropTypes - 애트리뷰트 값 타입 지정

이 기능을 통하여 특정 props값이 특정 type이 아니거나 필수 props인데 입력하지 않았을 경우 경고를 띄울 수 있다. Type을 검증할 때는 Component선언이 끝난 후, PropTypes를 설정하면 된다.

단, React v15.5부터 PropTypesReact에서 분리되었기 때문에 import를 꼭 해줘야 한다.

1
import PropTypes from 'prop-types';

그럼 아래의 예시를 보자.

PropsTest.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import React from 'react';
import PropTypes from 'prop-types';

export default class PropsTest extends React.Component {
render() {
return (
<div>
<h1>Hello { this.props.name }</h1>
<h2>{ this.props.children }</h2>
</div>

);
}
}

PropsTest.defaultProps = {
name: 'ellie'
};

PropsTest.propTypes = {
name: PropTypes.number
};

21번 줄에서 name애트리뷰트 값 타입을 number로 지정했다. 그런데, name에 지정한 값의 타입은 string이기 때문에 아래와 같이 에러가 발생한다.

Warning: Failed prop type: Invalid prop name of type string supplied to Props, expected number.



또한, 타입 지정 뒤에 isRequired를 붙여주면 이 애트리뷰트가 필수로 입력이 되도록 설정할 수 있다. propTypes를 아래와 같이 수정해보자.

1
2
3
4
PropsTest.propTypes = {
name: PropTypes.string,
age: PropTypes.number.isRequired
};

name애트리뷰트 값 타입을 string으로 지정해주었기 때문에 이 부분에서는 더 이상 에러가 발생하지 않는다. 하지만 age애트리뷰트 값 타입 지정 뒤에 isRequired를 붙여주었기 때문에 age애트리뷰트가 필수로 있어야 한다. 그런데 age애트리뷰트를 설정하지 않으면 아래와 같이 에러가 발생한다.

Warning: Failed prop type: The prop age is marked as required in Props, but its value is undefined.


PropTypes 종류

타입 지정 설명
PropTypes.string 문자열
PropTypes.array 배열
PropTypes.bool true/false
PropTypes.func 자바스크립트 함수
PropTypes.number 숫자
PropTypes.object 객체
PropTypes.symbol 자바스크립트 symbol
PropTypes.instanceOf(클래스명) 클래스 객체
PropTypes.oneOf([‘값1’, ‘값2’]) 두 값 중 하나
PropTypes.arrayOf(PropTypes.number) 숫자 배열


어떤 타입이든 필수로 입력이 되도록 설정하기

타입 지정 뒤에 isRequired를 붙여주면 된다. : PropTypes.any.isRequired

Share