Props 란?props는 React 컴포넌트 간에 데이터를 전달하기 위해 사용하는 속성(properties)이다.
부모 컴포넌트에서 자식 컴포넌트로 데이터를 전달할 때 주로 사용된다.
props는 읽기 전용이다.
이는 자식 컴포넌트에서 전달받은 props 값을 직접 수정할 수 없음을 의미한다.
예시
function Greeting({ name }) {
return <h1>안녕, {name}!</h1>;
}
<Greeting name='리액트' />;
결과 : 안녕, 리액트!
props.childrenprops.children은 컴포넌트 태그 사이에 포함된 자식 요소들을 나타낸다.
이를 활용하면 컴포넌트 내부에서 특정 위치에 자식 요소를 렌더링할 수 있다.
예시
function Card({ children }) {
return <div className='card'>{children}</div>;
}
<Card>
<h1>제목</h1>
<p>내용</p>
</Card>;
렌더링 결과
<div class="card">
<h1>제목</h1>
<p>내용</p>
</div>
🤹 활용 🤹
children은 단순히 텍스트나 HTML 요소뿐 아니라, 함수를 전달하여 동적인 렌더링도 가능하다.
예시
function Layout({ children }) {
return <div className="layout">{children()}</div>;
}
function App() {
return (
<Layout>
{() => (
<>
<h1>제목</h1>
<p>동적 콘텐츠</p>
</>
)}
</Layout>
);
}
defaultPropsprops가 전달되지 않았을 때 기본값을 설정하는 데 사용된다.
이는 컴포넌트에서 undefined나 누락된 props로 인해 발생할 수 있는 에러를 방지한다.
예시
function Button({ label }) {
return <button>{label}</button>;
}
Button.defaultProps = {
label: "클릭",
};
렌더링 결과
<button>클릭</button>
최신 문법
React 18 이상에서는 함수 매개변수의 기본값을 설정하는 방법도 지원된다.
function Button({ label = "클릭" }) {
return <button>{label}</button>;
}
props 활용 팁props 객체를 구조 분해 할당으로 분리하면 코드가 더 간결해집니다.
예시
function UserProfile({ name, age }) {
return (
<p>
{name}, {age}살
</p>
);
}
<UserProfile name="철수" age={20} />;
prop-types 패키지를 사용하여 props의 타입과 필수 여부를 정의하면 안정성과 가독성이 향상된다.
예시
import PropTypes from "prop-types";
function UserProfile({ name, age }) {
return (
<p>
{name}, {age}살
</p>
);
}
UserProfile.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number,
};
props 전달 줄이기children 활용하기props.children을 적극 활용하여 자식 요소를 유연하게 렌더링할 수 있다.