느려도 한걸음씩

children props로 재사용 가능한 컴포넌트 만들기 본문

FE develop/React

children props로 재사용 가능한 컴포넌트 만들기

hoj0806 2024. 12. 6. 14:58
function App() {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "10px" }}>
      <button
        style={{
          color: "red",
          background: "blue",
          width: "100px",
          height: "60px",
        }}
      >
        Next
      </button>
      <button
        style={{
          color: "red",
          background: "blue",
          width: "100px",
          height: "60px",
        }}
      >
        Previous
      </button>
      <button
        style={{
          color: "red",
          background: "blue",
          width: "100px",
          height: "60px",
        }}
      >
        Reset
      </button>
    </div>
  );
}

export default App;

 

UI 컴포넌트를 제작할때 재사용성을 높일수 있는 children props에 대해 알아보자

 

위의 코드는 3개의 버튼이 반복되어 사용되고 있고 그 안의 text만 다르게 표시되고 있다 이런 상황에서 children props를 유용하게 사용할수 있다

 

우선 Button 컴포넌트를 제작한다

 

function Button() {
  return (
    <button
      style={{
        color: "red",
        background: "blue",
        width: "100px",
        height: "60px",
      }}
    >
     
    </button>
  );
}

export default Button;

 

위의 코드를 참고해 Button 컴포넌트를 만들면 이런 모습일것이다 여기서 컴포넌트에 props를 넘겨주는데 children props를 넘겨준다

 

function Button({ children }) {
  return (
    <button
      style={{
        color: "red",
        background: "blue",
        width: "100px",
        height: "60px",
      }}
    >
      {children}
    </button>
  );
}

export default Button;

 

괄호를 이용해 children이 표시될 위치를 지정해준다 쉽게 표현하자면 컴포넌트에 구멍을 뚫어주는것과 같다 사용방법은 다음과 같다

 

import Button from "./Button";

function App() {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "10px" }}>
      <Button>Next</Button>
      <Button>Previous</Button>
      <Button>Reset</Button>
    </div>
  );
}

export default App;

 

Button 컴포넌트를 가져와 children의 내용을 태그 사이에 넣어주면된다 위의 예와 같이 단순 텍스트 뿐만 아니라 children으로 컴포넌트 자체를 넘겨주는것도 가능하다