props는 부모 컴포넌트로부터 받아온 데이터입니다.
우리는 컴포넌트 간의 정보를 교류할 때 Props를 사용합니다. 다른 컴포넌트는 생략하고 Mother만 봅시다. 만약 Mother 컴포넌트가 가지고 있는 정보(값)를 Child에게 주고 싶을 때는 아래 코드와 같이 합니다.
motherName이라는 이름으로 name 값을 Child 컴포넌트에게 전달해준 것입니다. 우리는 이 과정을 “Props 로 정보를 전달했다”
라고 표현합니다.
// src/App.js
import React from "react";
function Child() {
return <div>연결 성공</div>;
}
function Mother() {
const name = '홍부인';
return <Child motherName={name} />; // "props로 name을 전달했다."
}
function GrandFather() {
return <Mother />;
}
function App() {
return <GrandFather />;
}
export default App;
그러면, Mother가 전달해준 motherName은 Child가 어떻게 받을 수 있을까요? 이렇게 받습니다. 우리가 지금까지 한번도 관심있게 들여다보지 않았던 컴포넌트의 인자에서 props의 값을 받을 수 있습니다.
function Child(props){
console.log(props) // 이게 바로 props다.
return <div>연결 성공</div>
}
그럼 Mother
로부터 전달받은 motherName
을 화면에 렌더링 해볼까요?
import React from "react";
// div안에서 { } 를 쓰고 props.motherName을 넣어보세요.
function Child(props) {
return <div>{props.motherName}</div>;
}
function Mother() {
const name = "홍부인";
return <Child motherName={name} />;
}
function GrandFather() {
return <Mother />;
}
function App() {
return <GrandFather />;
}
export default App;
props는 object literal 형태이기 때문에 {props.motherName} 로 꺼내서 사용할 수 있습니다. object literal의 key가 motherName 인 이유는 우리가 Child로 보내줄 때 motherName={name} 으로 보내주었기 때문이죠.
object literal 란 {key: “value”} 데이터 형태를 의미합니다.
JSX에서는 HTML만 쓸 수 있는 줄 알았는데, 자바스크립트 코드를 사용했죠?
JSX에서도 { } 중괄호를 사용하면 자바스크립트 코드를 사용할 수 있습니다.
자식 컴포넌트에서는 부모 컴포넌트로 props를 전달할 수 없습니다. 오직 부모 컴포넌트에서 자식 컴포넌트로만 props를 전달할 수 있습니다.
부모 컴포넌트가 자식 컴포넌트에 데이터를 주는 방식이 2가지가 있다.
case01과 case02의 차이점을 보고 생각해보자.
//case01
function Child(props){
return(
<div>{props.grandfatherName}</div>)
}
function App(){
const [name, setName] = useState(초기값)
return (<Child grandfatherName={name} />
)
}
//case02
function Child(props){
return(<div>{props.children}</div>
)
}
function App(){
return(<Child>안녕하세요!</Child>
)
}