
Prop은 리액트에서 상위 컴포넌트가 하위 컴포넌트에 값을 전달할 때 사용하는 특성입니다. Props는 단방향 데이터 흐름을 가지며, 자식 컴포넌트에서는 수정할 수 없는 읽기 전용 데이터입니다.
" "), 그 외의 값(객체, 배열 등)은 중괄호({ })로 전달합니다.상위 컴포넌트에서 하위 컴포넌트에 데이터를 전달하는 기본적인 방법입니다.
// 상위 컴포넌트
const ParentComponent = () => {
return <ChildComponent title="Hello World" />;
};
// 하위 컴포넌트
const ChildComponent = (props) => {
return <h1>{props.title}</h1>;
};
여러 개의 Prop을 동시에 전달할 수 있습니다.
const ParentComponent = () => {
return <ChildComponent title="Hello" subtitle="Welcome!" />;
};
const ChildComponent = ({ title, subtitle }) => {
return (
<>
<h1>{title}</h1>
<h2>{subtitle}</h2>
</>
);
};
Props를 비구조화 할당을 통해 간편하게 사용할 수 있습니다.
const ChildComponent = ({ title, subtitle }) => {
return (
<>
<h1>{title}</h1>
<h2>{subtitle}</h2>
</>
);
};
props.childrenprops.children은 하위 컴포넌트 내에서 자식 요소를 렌더링할 때 사용됩니다. 이를 통해 컴포넌트 내부에 다른 컴포넌트를 포함할 수 있습니다.
const Wrapper = ({ children }) => {
return <div className="wrapper">{children}</div>;
};
// 사용 예시
const App = () => {
return (
<Wrapper>
<h1>Hello World</h1>
<p>This is a child component!</p>
</Wrapper>
);
};
상위 컴포넌트의 state를 하위 컴포넌트에 전달하여 연동할 수 있습니다.
import React, { useState } from 'react';
const ParentComponent = () => {
const [count, setCount] = useState(0);
return (
<div>
<h1>Count: {count}</h1>
<ChildComponent count={count} />
<button onClick={() => setCount(count + 1)}>Increase</button>
</div>
);
};
const ChildComponent = ({ count }) => {
return <h2>Current Count: {count}</h2>;
};
Props에 기본값을 설정할 수 있습니다. 이를 통해 컴포넌트가 Props를 받지 않았을 때 기본값을 제공할 수 있습니다.
const ChildComponent = ({ title, subtitle }) => {
return (
<>
<h1>{title}</h1>
<h2>{subtitle}</h2>
</>
);
};
ChildComponent.defaultProps = {
title: "Default Title",
subtitle: "Default Subtitle"
};
Props를 이용하여 조건부 렌더링을 수행할 수 있습니다. 특정 조건에 따라 컴포넌트의 내용이나 구조를 다르게 렌더링할 수 있습니다.
const Greeting = ({ isLoggedIn }) => {
return (
<div>
{isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please log in.</h1>}
</div>
);
};
// 사용 예시
const App = () => {
const [loggedIn, setLoggedIn] = useState(false);
return (
<div>
<Greeting isLoggedIn={loggedIn} />
<button onClick={() => setLoggedIn(!loggedIn)}>
Toggle Login
</button>
</div>
);
};
Prop은 리액트에서 컴포넌트를 연결하고 데이터를 전달하는 중요한 메커니즘입니다. 올바르게 사용하면 재사용성과 관리의 용이성을 극대화할 수 있습니다. 하지만 Prop Drilling이 과도해지지 않도록 주의하는 것이 중요하며, 필요한 경우 Context API 등의 대안을 고려하는 것이 좋습니다.
이렇게 Prop에 대한 내용을 더 자세히 정리해 보았습니다! 필요한 부분이나 추가할 내용이 있다면 언제든지 말씀해 주세요.