ReactJS/Prop Types

개기모·2023년 4월 12일
0

reactjs

목록 보기
3/5
post-thumbnail
<script src="
  https://unpkg.com/prop-types@15.7.2/prop-types.js"></script>

proptypes를 사용해보기 위해 간단히 불러온다.

const Btn = ({ text, fontSize = 22 }) => {
      console.log(text, "was rendered");
      return (
        <button
          style={{
            backgroundColor: "tomato",
            color: "white",
            padding: "10px 20px",
            border: 0,
            borderRadius: 10,
            fontSize,
          }}
        >
          {text}
        </button>
      );
    };
    Btn.propTypes = {
      text: PropTypes.string.isRequired,
      fontSize: PropTypes.number,
    };
    const App = () => {
      return (
        <div>
          <Btn text="Save Changes" fontSize={18} />
          <Btn text="Continue" />
        </div>
      );
    };

Prop types는 잘못된 형태의 type을 Property에 전달하는 걸 방지할 수 있도록 type을 체크할 수 있게 해준다.

Btn.propTypes에 설정한 것처럼 원하는 형태의 Property types를 지정하고, optional이 아닌 필수로 입력하도록 하고싶다면 .isRequired를 붙인다.

App()안에 두 번째 버튼처럼 optional property인 fontSize를 지정하지 않은 경우 Btn컴포넌트에서 default value 를 줄 수 있다. 그럼 fontsize가 지정되지 않은 두번째 버튼에만 적용된다.

https://reactjs.org/docs/typechecking-with-proptypes.html#proptypes 문서에서 proptypes 종류를 확인해보자.

profile
개발에 기역도 모르는게

0개의 댓글

Powered by GraphCDN, the GraphQL CDN