컴포넌트에 props 를 전달할 때 간혹 id나 className이나 style이 적용된 것들을 보내야할 때가 있는데 매번 그것들을 수동으로 보내고 수동으로 받는 것을 다 추가하다보면 번거로울 때가 있는데, 한번에 그것들을 넘길 수 있는 방법이 있다. 바로 해당 컴포넌트에 props를 보내고 ...props로 받는 방법이다.
<Section title="Examples" id='examples'>
</Section>
Section 컴포넌트에 title과 id props를 보내고
export default function Section({children, ...props}){
return(
<section {...props}>
<h2>{props.title}</h2>
{children}
</section>
);
}
Section 컴포넌트에서 ...props로 받아 id값이 들어갈 자리에 ...prop로 css를 적용하는 것이다.
또 다른 예시는
<TabButton key={i} isselected={selectedTopic ? selectedTopic.title : ""}
onClick={() => handleSelect(value)} title={value.title}></TabButton>
TabButton 컴포넌트에 여러 props를 보낸 후,
export default function TabButton({...props}) {
return (
<li {...props}>
<button className={props.isselected === props.title ? "active" : ""}
{...props}>
</button>
</li>
)
}
TabButton 컴포넌트에서 ...props로 내장 함수들과 값들을 적용시킬 수 있다.
li {...props} 에는 key 값이 들어갈 것이고
className 뒤에 오는 {...props} 는 onclick에 해당되는 props이다.
따라서 props를 넘길 때 어떠한 조건을 걸지 않는 이상 여러 props들을 {...props} 로 받음으로써 한꺼번에 적용할 수 있는 좋은 방법이라는 것을 알 수 있다!