
자바스크립트 객체로 이미 구성된 데이터가 있다면, 그 객체를 여러 Prop들로 나누는 대신 하나의 Prop 값으로 전달할 수 있습니다.
즉,
<CoreConcept
title={CORE_CONCEPTS[0].title}
description={CORE_CONCEPTS[0].description}
image={CORE_CONCEPTS[0].image} />
또는
<CoreConcept
{...CORE_CONCEPTS[0]} />
대신,
이처럼 CoreConcept 컴포넌트에 하나의 concept Prop를 전달할 수 있습니다 (Prop 이름은 선택적):
<CoreConcept
concept={CORE_CONCEPTS[0]} />
그러면 CoreConcept 컴포넌트에서는 그 하나의 Prop만 받게 됩니다:
export default function CoreConcept({ concept }) {
// Use concept.title, concept.description etc.
// Or destructure the concept object: const { title, description, image } = concept;
}
어떤 문법과 접근 방식을 선호하는지는 전적으로 나의 선택!
여러 Prop을 컴포넌트에 전달한 다음, 컴포넌트 함수 내에서 자바스크립트의 "Rest Property" 문법을 사용하여 단일 객체로 그룹화할 수도 있습니다.
예를 들어, 컴포넌트가 이런 식으로 사용되었다면:
<CoreConcept
title={CORE_CONCEPTS[0].title}
description={CORE_CONCEPTS[0].description}
image={CORE_CONCEPTS[0].image} />
받은 prop들을 다음과 같이 단일 객체로 그룹화할 수 있습니다:
export default function CoreConcept({ ...concept }) {
// ...concept groups multiple values into a single object
// Use concept.title, concept.description etc.
// Or destructure the concept object: const { title, description, image } = concept;
}
가끔 선택적 Prop을 받을 수 있는 컴포넌트를 만들게 될 때가 있습니다.
예를 들어, ‘type’ Prop을 받을 수 있는 커스텀 Button 컴포넌트가 있습니다.
그러면 Button 컴포넌트는 type 설정 여부와 상관 없이 모두 사용할 수 있어야 합니다.
type 설정이 된 경우:
<Button type="submit" caption="My Button" />
되지 않은 경우:
<Button caption="My Button" />
이 컴포넌트가 작동하도록 하려면, type Prop에 대한 기본 값을 설정할 수 있습니다 - 전달되지 않을 경우를 대비하는 것입니다.
자바스크립트는 객체 비구조화를 사용할 때 기본 값을 지원함으로 이를 쉽게 달성할 수 있습니다:
export default function Button({ caption, type = "submit" }) {
// caption has no default value, type has a default value of "submit"
}
Prop에서 구조 분해 할당(Destructuring Assignment)
function CoreConcept(props) {
return (
<div>
<h1>{props.title}</h1>
<p>{props.description}</p>
<img src={props.image} alt={props.title} />
</div>
);
}
// 사용:
<CoreConcept title="React Basics" description="Learn the basics of React." image="react-basics.png" />
여기서는
CoreConcept 컴포넌트에 title, description, image라는 Prop들을 전달하고 있다.
이 Prop들은 props 객체로 전달되고,
각각 props.title, props.description, props.image로 접근하고 있습니다.
구조 분해 할당을 사용하면, 전달된 props 객체에서 원하는 속성들을 쉽게 꺼내어 사용할 수 있습니다.
function CoreConcept({ title, description, image }) {
return (
<div>
<h1>{title}</h1>
<p>{description}</p>
<img src={image} alt={title} />
</div>
);
}
이 방법에서는 props 객체를 받아서 { title, description, image }처럼 구조 분해 할당을 통해 필요한 속성들을 꺼내옵니다.
이제 컴포넌트 내부에서 props.title 대신 title만으로 값을 사용할 수 있습니다.
구조 분해 할당은 기본 값 설정과도 함께 사용할 수 있습니다. 기본 값을 설정하면, 해당 Prop이 전달되지 않았을 때 기본 값이 자동으로 사용됩니다.
function Button({ caption, type = "button" }) {
return <button type={type}>{caption}</button>;
}
여기서 type Prop이 전달되지 않으면, type은 기본적으로 "button"이 됩니다.
예를 들어, 다음 중 문구 “Priority:5”를 화면에 출력하지 않는 코드는?
1️⃣
<MyComponent priority={5} />
function MyComponent({...props}) {
return <p>Priority: {props.priority}</p>
}
//이 코드는 spread 연산자 ...props를 사용하여 모든 Prop을 props 객체에 수집합니다.
//여기서 props.priority는 올바르게 5로 설정됩니다.
//따라서 이 코드는 “Priority: 5”를 화면에 출력합니다.
2️⃣
<MyComponent priority={5} />
function MyComponent(props) {
return <p>Priority: {props.priority}</p>
}
//이 코드는 props 객체를 통째로 받아 props.priority로 Prop 값을 접근합니다.
//이 역시 올바르게 작동하여 “Priority: 5”를 출력합니다.
3️⃣
<MyComponent priority={5} />
function MyComponent({priority}) {
return <p>Priority: {priority}</p>
}
//여기서는 구조 분해 할당을 사용해 priority Prop을 직접 추출합니다.
//이 방법도 올바르게 작동하여 “Priority: 5”를 출력합니다.
4️⃣
<MyComponent priority={5} />
function MyComponent(priority) {
return <p>Priority: {priority}</p>
}
//이 코드에서는 문제가 있습니다. priority를 단일 인수로 받고 있지만,
//React 컴포넌트는 첫 번째 인자로 props 객체를 전달받습니다.
//따라서 priority 변수는 실제로는 props 객체 전체를 참조하게 되고,
//이는 priority 값이 아닙니다. 결과적으로 이 코드는 “Priority: 5”를 출력하지 못하고
//undefined를 출력하거나 오류를 발생시킬 수 있습니다.