interface Props {
iconStr: string
text: string
}
export default function IconText({ iconStr, text }: Props){
const icon = {
star: <Star />,
circle: <Circle />,
triangle: <Triangle />,
square: <Square />,
}[iconStr]
return (
<>
{icon}
<div>{text}</div>
</>
)
}
위 컴포넌트에 props로 들어오는 iconStr
를 icon
객체를 선언하면서 key를 바로 받아 해당하는 값은 반환합니다. icon
객체를 저런 형태를 만들지 않으면 if나 switch문을 이용해 분기하는 코드를 작성해야 합니다. 번거롭습니다. 조건문을 사용할 때 그 대신 객체 key-value구조로 간단하게 할 수 있는 지 생각해봅시다.