Tech Blog of Pinomaker

React props의 타입 문제

React는 props에 매개 변수를 넘길 때 타입 검사를 하지 않는다. 

나는 Number 자료형으로 넘겨 받고 싶지만, 만약 String이 넘겨와도 문제가 되지 않는다

Document
const Age = (props) => {
    return <h1>{props.age}</h1>
}

const App = () => {
    return(
        <div>
        <Age age = {3} />
        <Age age = "3" />
        </div>
    )
}

위와 같은 경우가 생기기에, 좀 더 타입을 명확히 해주기 위해서 PropsTypes 기능을 사용한다.

 

//prop-types 모듈을 설치한다.

npm install prop-types

 

Proptypes 사용 방법

이제 <Age age = "3" />을 사용하게 되면 타입이 맞지 않아 문제가 된다.

const Age = (props) => {
    return <h1>{props.age}</h1>
}

Age.propTypes = {
	age : PropTypes.string
}

const App = () => {
    return(
        <div>
            <Age age = {3} />
            <Age age = "3" />
        </div>
    )
}

 

profile

Tech Blog of Pinomaker

@pinomaker

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!