Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- nextjs 설치
- git lab
- CSS
- input type=file
- SCSS
- Git
- ngrok실행
- next.js css
- There isn’t anything to compare
- createGlobalStyle
- dart 변수
- styled components
- react typescript
- nextjs
- API token
- fetch
- rewrites
- bootstrap
- getModifierState
- npm styled-reset
- github io
- 컨디셔널 렌더링
- github
- ngrok설치
- icon
- typescript react
- react env
- nextjs .env
- react
- API 토큰
Archives
- Today
- Total
꾸준히 성장하는 개발자
[React] props type 본문
react에서는 props의 데이터 타입을 잘못 입력해도 문법상 문제가 없다면 에러메시지 없이 화면 출력이 된다
function App() {
return (
<div>
<Btn text="Save Change" fontSize={18} />
<Btn text={16} fontSize={"value"} />
</div>
);
}
const root = document.getElementById("root");
ReactDOM.render(<App />, root);
<Btn text="Save Change" fontSize={18} />
<Btn text={16} fontSize={"value"} />
text prop에는 string으로 써야 하고 fontSize prop에는 숫자로 작성을 해야 하는데
이렇게 작성이 되어도 react에서는 오류로 인지하지 못하고
화면에 출력이 되게 된다.
이런 경우에 이런 실수를 막을 수 있도록 하는 방법이 props type이다
<script src="https://unpkg.com/prop-types@15.7.2/prop-types.js"></script>
이걸 위에 추가해주고
Btn.propTypes = {
text: PropTypes.string,
fontSize: PropTypes.number,
};
function App() {
return (
<div>
<Btn text="Save Change" fontSize={18} />
<Btn text={16} fontSize={"value"} />
</div>
);
}
const root = document.getElementById("root");
ReactDOM.render(<App />, root);
컴포넌트이름 . propTypes = {
prop이름 : PropTyps . 작성해야 하는 data type ,
prop이름 : PropTyps . 작성해야 하는 data type ,
};
예시)
Btn.propTypes = {
text: PropTypes.string,
fontSize: PropTypes.number,
};
이 방식으로 작성하여 추가해준다.

이렇게 되면 잘못 작성된 코드가 화면에 출력되더라도 console창에 에러 메시지를 보내주면서
어디가 틀렸는지 확인할 수 있다.
만약 컴포넌트가 필수적으로 써야 하는 props를 놓치지 않고 render 되게 하길 원한다면
. isRequired를 추가로 작성해준다.
예시)
Btn.propTypes = {
text: PropTypes.string.isRequired,
fontSize: PropTypes.number.isRequired,
};
화면은 출력되지만 console창에 에러 메시지를 띄워 확인이 가능하다
npm을 이용한 prop types
npm i prop-types을 터미널에 작성하고 install 한다
import PropTypes from "prop-types";
function Button({ text }) {
return <button>{text}</button>;
}
Button.propTypes = {
text: PropTypes.string.isRequired,
};
export default Button;
위에 import 하고 아래 작성하는 법은 위와 같다/
'React' 카테고리의 다른 글
[React]useState( ) (0) | 2022.04.27 |
---|---|
[React]styled-component 를 이용한 theme (0) | 2022.03.01 |
[react] Ant Design (0) | 2022.02.10 |
[react] react-shadow (0) | 2022.02.09 |
[react] styled-component 정리하기 (1) | 2022.02.08 |