본문 바로가기
FrontEnd/React

[ReactJS] Prop Types

by kurooru 2023. 1. 9.

지난 시간에는 함수의 인수처럼 React는 Component를 불러올 때 인수를 전달할 수 있다고 배웠다.

이번 시간에는 만약 이러한 인수가 잘못된 형식으로 전달되면? 에 대한 질문이다.

지극히 인간적 관점인 것이, 개발을 하다보면 이런 실수를 자주 하게 되기 때문이다.

애석하게도 리액트는 이를 '잘못된 문법' 이라 우리에게 알려주지 않는다.

왜냐하면 엄밀히 말해 이는 틀린 문법이 아니라 잘못 말한거기 때문이다.

영어 스피킹을 할 때 문법은 맞는데 안에 내용이 다 틀린 그런 느낌?

'Hello I am kurooru' 라고 말할려 했는데

'Fxxk U'라고 말한 느낌이다.

후자도 절대 틀린 문법은 아닐것이다.

그러나 전달할려고 하는 의미는 완전히 틀렸다.

인간이기 때문에 일어나는 지극히 인간적 오류다.

그러나 친절하게도 리액트는 이에 대한 해법까지 제시해준다.

이것은 우리가 직접 리액트에게 여기에는 이걸 넣어줘~ 라는 식으로 미리 설정을 할 수 있게 하는 것이다.

 

아래 코드를 살펴보자

<!DOCTYPE html>
<html lang="en">
  <body>
    <div id="root"></div>
  </body>
  
  <!-- How to import React(engine) -->
  <script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script>
  <!-- How to import React-dom(put elements into HTML) -->
  <script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.production.min.js"></script>
  <!-- How to notice React Js which type props must be (preventing error causing by developer) -->
  <script src="https://unpkg.com/prop-types@15.7.2/prop-types.js"></script>
  <!-- How to make browser read JSX syntax (using babel)-->
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
  <!-- How to use babel (reading JSX syntax properly) -->
  <script type="text/babel">
    
    function Btn({text, fontSize=14}) { // We can set default value (fontSize)
      return (
      <button
        style={{backgroundColor:"tomato", color:"white", padding:"10px 20px", border:0, borderRadius:10, fontSize: fontSize}}
        >
        {text}
      </button>
      )
    };
    
    // Inspect every property's type
    // If the property doesn't have proper datatype, it will send you a error msg.
    Btn.propTypes = {
      text: PropTypes.string,
      fontSize: PropTypes.number,
    };

    function App () {
      return (
        <div>
          <Btn text="Save Changes" fontSize={18}/>
          <Btn text="continue"/>
        </div>
      )
    };

    // find id="root" from document(HTML)
    const root = document.getElementById("root");
    
    // initial render
    ReactDOM.render(<App />, root);
  </script>
</html>

이와 같은 필터 기능을 사용하기 위해서는

  <!-- How to notice React Js which type props must be (preventing error causing by developer) -->
  <script src="https://unpkg.com/prop-types@15.7.2/prop-types.js"></script>

propTypes를 설치해줘야 한다.

그리고

    // Inspect every property's type
    // If the property doesn't have proper datatype, it will send you a error msg.
    Btn.propTypes = {
      text: PropTypes.string,
      fontSize: PropTypes.number,
    };

이런식으로 text는 string이여야 하며,

fontSize는 number이여야만 한다는 사실을 미리 리액트에게 교육시켜줘야 한다.

 

이렇게 하면 잘못된 인수를 넣었을 때,

이와 같이 똑바로 인수 넣으라고 경고를 친절히 띄워준다.

'FrontEnd > React' 카테고리의 다른 글

[ReactJS] useEffect()  (0) 2023.01.11
[ReactJS] useEffect  (0) 2023.01.10
[ReactJS] memo  (0) 2023.01.09
[ReactJS] prop  (0) 2023.01.09
[ReactJS] prop에 대한 이해  (0) 2023.01.08