🔥 문제
다이나믹한 태그 설정을 위해 타입스크립트로 작성 중,
JSX.intrinsicElement
에 해당 변수 값이 없다는 오류가 발생했다.
다음은 해당 문제가 발생했던 코드이다.
import React, { ReactNode } from 'react'; interface TagType { HeaderTag: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6'; } export interface HeaderTextProps { children: ReactNode; level: 1 | 2 | 3 | 4 | 5 | 6; [prop: string]: any; } const HeaderText = ({ children, level = 1 }: HeaderTextProps) => { const headerTag = `h${level}` as TagType; return <headerTag>{children}</headerTag>; }; export default HeaderText;
⭐ 해결 방법
가장 결정적인 해결 방법을 제공한 링크는
Stackoverflow
의 해당 토론 글이었다.결국 내가 2가지 실수를 저질렀는데,
- 인터페이스를 사용했다는 것.
인터페이스를 사용할 때는 객체일 때가 가장 적합하다. 객체가 아닐 때에는
type
을 통해 간단히 각 변수의 타입을 설정해야 한다.type TagType = 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6';
- 문자를 대문자의 형식을 따르지 않았다는 것.
어차피 나는 문자야 뭐... 값이 할당되니까 잘 인식하지 않나? 싶었는데, 결국
JSX
의 가장 큰 컨벤션이 '변수로 설정했을 때 해당 이름은 PascalCase
을 따라야 한다'는 것이었기에 이를 제대로 지키지 않았다는 것이었다.따라서 이를 다시 재설정해줬다.
import React, { ReactNode } from 'react'; type TagType = 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6'; export interface HeaderTextProps { children: ReactNode; level: 1 | 2 | 3 | 4 | 5 | 6; [prop: string]: any; } const HeaderText = ({ children, level = 1 }: HeaderTextProps) => { const HeaderTag = `h${level}` as TagType; return <HeaderTag>{children}</HeaderTag>; }; export default HeaderText;
이제 오류가 나지 않는다!
배운 점
- 변수같은 것들은 간단하게 타입으로 해당 변수의 타입을 설정해주자!
PascalCase
는 JSX 확장자 형식에서는 국룰이다!
향후 나는
CarrotFrame
에 꽂혀서 리액트 기반 새로운 패키지를 만들 계획을 갖고 있는데, 이러한 규칙을 꼭 잊지 말아야겠다 🙂