[React] props.children

App.js
import Wrapper from "./Wrapper";
import Hello from "./Hello";

function App() {
return (
<Wrapper>
<Hello></Hello>
<Hello></Hello>
</Wrapper>
);
}

export default App;



Wrapper.js
import React from "react";

const Wrapper = ({ children }) => {
const style = {
border: "1px solid black",
padding: "16px",
margin: "5px",
};
return <div style={style}>{children}</div>;
};

export default Wrapper;



Hello.js
import React from "react";

const Hello = () => {
return <div>test</div>;
};

export default Hello;



최상위 태그가 아닌 컴포넌트 사이에 컴포넌트를 작성하면 상위 컴포넌트에 감싸져있는 하위 컴포넌트들은 출력되지 않는다.

컴포넌트 사이에 작성된 컴포넌트를 출력하기 위해서는 props.children을 사용해야 한다.

감싸고 있는 상위 컴포넌트 즉, 부모 컴포넌트는 props.children 으로 컴포넌트 중간에 작성한 컴포넌트들을 받아 올 수 있다.

위 예시에서  Wrapper 컴포넌트가 하위 컴포넌트를 감싸고있는 상위 컴포넌트이기 때문에  props.children 으로 하위 컴포넌트들을 받을 수 있다.

여기서 props.children이 아닌 children을 바로 사용할 수 있는 이유는 구조분해할당 문법을 사용해서 가능하다.




이외에도 한가지 추가적인 예시를 보면

App.js
import Button from "./components/Button";

const App = () => {
return (
<div className="App">
<Button>Button</Button>
</div>
);
};

export default App;



Button.js
import React from "react";
import "./Button.scss";

const Button = ({ children }) => {
return <button className="Button">{children}</button>;
};

export default Button;



컴포넌트안에 컴포넌트가 아니더라도 컴포넌트 사이에 작성한 값을 props.children으로 받아 출력할 수 있다.






댓글