배경
- li를 커스텀한 컴포넌트에 key를 props로 넘겨줄 때 해당 이슈 발생
const Content = (props: {
parentClassName: string;
key: string;
src: string;
alt: string;
title: string | undefined;
category: string | null;
}) => {
const { key, parentClassName, src, alt, title, category } = props;
return (
<li
key={key}
css={css`
display: flex;
align-items: center;
`}
className={`${parentClassName}__content`}
>
<div
css={css`
width: 20px;
height: 20px;
`}
className={`${parentClassName}__image-container`}
>
<img
css={css`
width: 100%;
height: 100%;
`}
className={`${parentClassName}__image`}
src={src}
alt={alt}
/>
</div>
<p> {title} </p>
<span> {category || ''} </span>
</li>
);
};
const SearchResultBase: FunctionComponent<Results & { className?: string }> = ({ results, className = '' }) => {
return results.length > 0 ? (
<ul className={className}>
{results.map((result) => {
return (
<Content
key={result._id}
src={result.image || '/images/post-index.svg'}
alt={result.image ? '유저이미지' : '뽀모도르 글 목차 이미지'}
title={result.fullName || result.title}
category={(result.channel && result.channel?.name) || null}
/>
);
})}
</ul>
) : (
<></>
);
};
해결
- key는 React 자체적으로 사용되는 special props 중 하나이기 때문에 임의로 자식 컴포넌트 props로 넘겨주면 안된다.
const Content = (props: { src: string; alt: string; title: string | undefined; category: string | null }) => {
const { src, alt, title, category } = props;
return (
<li
css={css`
display: flex;
align-items: center;
`}
>
<div
css={css`
width: 20px;
height: 20px;
`}
>
<img
css={css`
width: 100%;
height: 100%;
`}
src={src}
alt={alt}
/>
</div>
<p> {title} </p>
<span> {category || ''} </span>
</li>
);
};
const SearchResultBase: FunctionComponent<Results & { className?: string }> = ({ results, className = '' }) => {
return results.length > 0 ? (
<ul className={className}>
{results.map((result) => {
return (
<Content
key={result._id}
src={result.image || '/images/post-index.svg'}
alt={result.image ? '유저이미지' : '뽀모도르 글 목차 이미지'}
title={result.fullName || result.title}
category={(result.channel && result.channel?.name) || null}
/>
);
})}
</ul>
) : (
<></>
);
};