작업환경
- nextjs
- typescript
- airbnb styleguide
에러 발생 상황
부모 컴포넌트로부터 props로 num 을 받아오는 자식 컴포넌트인 item 컴포넌트에서 props 값에 따른 각기 다른 css 스타일 적용을 위해 삼항연산자를 사용하였는데, do not nest ternary expression 라는 에러가 발생하였다.
아마도 airbnb 스타일 가이드 때문에 발생한 에러가 아닌가 싶다.
<div
className={`${styles.itemInfo} ${
num === '01'
? styles.typeOne
: num === '02'
? styles.typeTwo
: styles.typeThree
}`}
>
첫번째 시도
삼항연산자를 switch 문으로 대체 하였으나 string 값 자체가 클래스명으로 적용되어서 module.css 가 적용되지 않았다.
let types = 'styles.typeOne';
switch (num) {
case '01':
types = 'styles.typeOne';
break;
case '02':
types = 'styles.typeTwo';
break;
case '03':
types = 'styles.typeThree';
break;
default:
types = 'styles.typeOne';
}
return (
<div className={`${styles.itemInfo} ${types}`}>
두번째 시도
let types = 'styles.typeOne';
switch (num) {
case '01':
types = 'typeOne';
break;
case '02':
types = 'typeTwo';
break;
case '03':
types = 'typeThree';
break;
default:
types = 'typeOne';
}
return (
<div className={`${styles.itemInfo} ${types}`}>
...
페이지는 랜더링이 된다. 그러나 맨 위에서 파일 구조를 보았다시피 현재 프로젝트는 css를 module로 만들어 관리하고 있기 때문에 className은 반드시 styles.[클래스명] 이 되어야 하는데, 이렇게 할 경우 styles가 빠져있기 때문에 css 모듈이 적용되지 않는다.
해결
return (
<div
className={`${styles.itemInfo}
${num === '01' ? styles.typeOne : ''}
${num === '02' ? styles.typeTwo : ''}
${num === '03' ? styles.typeThree : ''}
`}
>
참고자료
pluralsight.com/guides/applying-classes-conditionally-react
또 다른 에러
Dangerous property 'dangerouslySetInnerHTML' found
...
const itemDate = [
{...
const adnDescription =
'첫번째줄<br/>두번째줄';
},
{...
const adxDescription =
'첫번째줄<br/>두번째줄<br/>세번째줄';
},
{...
const crmDescription =
'첫번째줄<br/>두번째줄';
},
];
return (
...
<dd
dangerouslySetInnerHTML={{
__html:
num === '01'
? adnDescription
: num === '02'
? adxDescription
: crmDescription,
}}
/>
...
해결
...
const itemData = [
{...
const adnDescription = [
'첫번째줄',
'두번째줄';
],
},
{...
const adxDescription = [
'첫번째줄',
'두번째줄',
'세번째줄';
],
},
{...
const crmDescription = [
'첫번째줄',
'두번째줄';
],
},
],
return (
...
<dd
{description.map((item) => (
<span key={item}>
{item} <br />
</span>
))}
/>
...
'React' 카테고리의 다른 글
React | 구글 리캡챠(reCaptcha) v2 사용하기 (0) | 2022.02.25 |
---|---|
React | 카카오 맵 API 사용하여 지도 띄우기 (0) | 2022.02.23 |
React | 동적 라우팅 (0) | 2022.01.26 |
React | props와 state (0) | 2022.01.14 |
React | 로그인 버튼 활성화(React를 이용하여) (0) | 2022.01.13 |