4.2 Prop Types

2022. 9. 15. 14:21React/ReactJS로 영화 웹 서비스 만들기

자 이번에는 너무 많은 Props를 가지다가 실수를 저질렀을 때를 한번 살펴보자.

 

Btn에 한가지 더 configuration(설장)을 해보자.

user가 prop으로 fontSize를 전달할 수 있도록 해보자.

<!DOCTYPE html>
<html lang="en">

<body>
    <div id="root"></div>
</body>
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
    function Btn({ text, fontSize }) {
        return (
            <button
                style={{
                    backgroundColor: "tomato",
                    color: "white",
                    padding: "10px 20px",
                    border: 0,
                    borderRadius: 10,
                    fontSize,
                }}
            >
                {text}
            </button>
        );
    }
    const MemorizedBtn = React.memo(Btn);
    function App() {
        return (
            <div>
                <Btn text="Save Changes" fontSize={18} />
            </div>
        )
    }
    const root = document.getElementById("root");
    ReactDOM.render(<App />, root);
</script>

</html>

 

근데 여기서 prop을 string을 보내야하는데 number를 전송한 경우! 아니면 그 반대의 경우!

그러면 error는 나지 않지만

문제는 React가 이 문제를 알아차리지 못한다는 것이다.

 

근데 이를 해결해주는 툴이 있는데

PropTypes라는 패키지가 있다.

PropTypes는 어떤 타입의 prop을 받고 있는지를 체크해준다!

https://unpkg.com/prop-types@15.7.2/prop-types.js

그래서 아래의 코드를 추가해주면 된다.

<script src="https://unpkg.com/prop-types@15.7.2/prop-types.js"></script>

 

    Btn.propTypes = {
        text: PropTypes.string,
        fontSize: PropTypes.number,
    }

그럼 prop의 타입을 알려주고 에러가 다음과 같이 나는 것을 알 수 있다.

근데 여기서 잠깐, 이렇게 안나오는 사랆들은 

script에서 production.min.js가 아닌 development.js로 변경해야한다!!!!!!!!!!!

<!DOCTYPE html>
<html lang="en">

<body>
    <div id="root"></div>
</body>
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/prop-types@15.7.2/prop-types.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
    function Btn({ text, fontSize }) {
        return (
            <button
                style={{
                    backgroundColor: "tomato",
                    color: "white",
                    padding: "10px 20px",
                    border: 0,
                    borderRadius: 10,
                    fontSize,
                }}
            >
                {text}
            </button>
        );
    }
    Btn.propTypes = {
        text: PropTypes.string,
        fontSize: PropTypes.number,
    }
    function App() {
        return (
            <div>
                <Btn text="Save Changes" fontSize={18} />
                <Btn text={14} fontSize={"Continue"} />
            </div>
        )
    }
    const root = document.getElementById("root");
    ReactDOM.render(<App />, root);
</script>

</html>

그래서 다음과 같이 정상적으로 코드를 변경하게 된다면

화면이 정상적으로 출력되는 것을 볼 수 있다.

 

다음은 prop type들에 대한 예제소스이다.

PropTypes
다른 유효성 검사리를 제공하는 예제 문서입니다.

import PropTypes from 'prop-types';

MyComponent.propTypes = {
  // You can declare that a prop is a specific JS primitive. By default, these
  // are all optional.
  optionalArray: PropTypes.array,
  optionalBool: PropTypes.bool,
  optionalFunc: PropTypes.func,
  optionalNumber: PropTypes.number,
  optionalObject: PropTypes.object,
  optionalString: PropTypes.string,
  optionalSymbol: PropTypes.symbol,

  // Anything that can be rendered: numbers, strings, elements or an array
  // (or fragment) containing these types.
  optionalNode: PropTypes.node,

  // A React element.
  optionalElement: PropTypes.element,

  // You can also declare that a prop is an instance of a class. This uses
  // JS's instanceof operator.
  optionalMessage: PropTypes.instanceOf(Message),

  // You can ensure that your prop is limited to specific values by treating
  // it as an enum.
  optionalEnum: PropTypes.oneOf(['News', 'Photos']),

  // An object that could be one of many types
  optionalUnion: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
    PropTypes.instanceOf(Message)
  ]),

  // An array of a certain type
  optionalArrayOf: PropTypes.arrayOf(PropTypes.number),

  // An object with property values of a certain type
  optionalObjectOf: PropTypes.objectOf(PropTypes.number),

  // An object taking on a particular shape
  optionalObjectWithShape: PropTypes.shape({
    color: PropTypes.string,
    fontSize: PropTypes.number
  }),

  // You can chain any of the above with `isRequired` to make sure a warning
  // is shown if the prop isn't provided.
  requiredFunc: PropTypes.func.isRequired,

  // A value of any data type
  requiredAny: PropTypes.any.isRequired,

  // You can also specify a custom validator. It should return an Error
  // object if the validation fails. Don't `console.warn` or throw, as this
  // won't work inside `oneOfType`.
  customProp: function(props, propName, componentName) {
    if (!/matchme/.test(props[propName])) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'
      );
    }
  },

  // You can also supply a custom validator to `arrayOf` and `objectOf`.
  // It should return an Error object if the validation fails. The validator
  // will be called for each key in the array or object. The first two
  // arguments of the validator are the array or object itself, and the
  // current item's key.
  customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {
    if (!/matchme/.test(propValue[key])) {
      return new Error(
        'Invalid prop `' + propFullName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'
      );
    }
  })
};

출처 : https://reactjs-kr.firebaseapp.com/docs/typechecking-with-proptypes.html

 

Typechecking With PropTypes – React

A JavaScript library for building user interfaces

reactjs.org

 

다음 코드에서 두번째 버튼에는 fontSize를 명시하지 않고

컴포넌트가 이 두 prop들만 정확히 갖고 render될 것이라는 걸 확실히 하고 싶다면 

isRequired

를 추가해주면 된다.

(이것이 들어가면 반드시 이 prop을 분명히 가지고 있어야한다고 명시해주는 것이다.)

그래서 다음과 같이 fontSize가 undefined되어있다고 알려주는 것을 확인할 수 있다.

그래서 우선 text에만 isRequired로 설정해주자!

 

 

 

default value(기본 값)을 설정 (JavaScript로!)

기본값은 다음과 같이 설정할 수 있다.

이때는 undefined일때, 그 값에는 기본값이 들어가게 되는 것이다!

그래서 두번째 버튼에만 이 fontSize가 적용된다! (undefined이니까!)

 

전체 코드

<!DOCTYPE html>
<html lang="en">

<body>
    <div id="root"></div>
</body>
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/prop-types@15.7.2/prop-types.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
    function Btn({ text, fontSize = 12 }) {
        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,
    }
    function App() {
        return (
            <div>
                <Btn text="Save Changes" fontSize={18} />
                <Btn text={"Continue"} />
            </div>
        )
    }
    const root = document.getElementById("root");
    ReactDOM.render(<App />, root);
</script>

</html>

'React > ReactJS로 영화 웹 서비스 만들기' 카테고리의 다른 글

5.0 Introduction  (0) 2022.09.15
4.3 Recap  (0) 2022.09.15
4.1 Memo  (0) 2022.09.14
4.0 Props  (0) 2022.09.14
3.9 Final Practice and Recap  (0) 2022.09.14