1 분 소요

리액트에서의 슬롯(Slot)이란?

자식 컴포넌트를 삽입할 수 있는 영역

컴포넌트 내 다양한 슬롯 설정 방법

1. children

children 이라는 이름의 prop으로 부모 컴포넌트의 자식 영역에 삽입

2. 명시적인 슬롯

각 슬롯을 구분할 수 있도록 props의 이름을 지정해 명시적으로 전달
강의에 나오는 JSX 요소(컴포넌트)를 전달하는 패턴 또한 명시적인 슬롯 방법 중 하나인듯하다.

function Tabs({ buttons, children }) {
  return (
    <div>
      <div className="tabs">{buttons}</div>
      <div className="content">{children}</div>
    </div>
  );
}
function Parent() {
  const [selectedTopic, setSelectedTopic] = useState("a");
  return (
    <Tabs
      buttons={
        <>
          <TabButton
            isSelected={selectedTopic === "a"}
            onClick={() => setSelectedTopic("a")}
          >
            Tab A
          </TabButton>
          <TabButton
            isSelected={selectedTopic === "b"}
            onClick={() => setSelectedTopic("b")}
          >
            Tab B
          </TabButton>
        </>
      }
    >
      {selectedTopic === "a" && <div>Content A</div>}
      {selectedTopic === "b" && <div>Content B</div>}
    </Tabs>
  );
}

3. render props, children as a function 패턴을 이용한 슬롯

자식 컴포넌트가 어떻게 렌더링될지를 부모 컴포넌트에서 함수 형태로 전달하여, 동적인 콘텐츠를 제어하는 방법 → 부모 컴포넌트는 자식 컴포넌트에게 렌더링할 방식에 대한 로직을 제공하고 자식 컴포넌트는 전달받은 로직을 실행해 콘텐츠를 렌더링

마지막 render props, children as a function 패턴은 익숙치 않아서 좀 더 찾아보았다 🤔

render props

props로 자식 컴포넌트에 함수를 전달하는 방식

// 부모
function App() {
  const fruits = ["Apple", "Banana", "Mango"];
  return (
    // renderItem 이라는 props 함수를 자식에 전달
    <List
      fruits={fruits}
      renderItem={(item, index) =>
        index % 2 === 0 ? <strong>{item}</strong> : <del>{item}</del>
      }
    />
  );
}

// 자식
function List({ fruits, renderItem }) {
  return (
    <ul>
      {fruits.map((fruit, index) => (
        <li key={index}>{renderItem(fruit)}</li>
        //전달받은 함수를 실행해 렌더링
      ))}
    </ul>
  );
}

children as a function

children을 함수로 전달받는 방법

// 부모 컴포넌트
function Parent() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <h1>Count:{count}</h1>
      {/* Button 컴포넌트의 children을 함수로 전달*/}
      <Button>
        {(handleClick) => (
          <button onClick={() => handleClick(setCount)}> + </button>
        )}
      </Button>
    </div>
  );
}

// 자식 컴포넌트
function Button({ children }) {
  //자식에서 함수를 실행하면 자식이 부모의 상태를 변경
  const handleClick = (setCount) => {
    setCount((prev) => prev + 1);
  };
  //children을 함수로 실행
  return <div>{children(handleClick)}</div>;
}

댓글남기기