React 컴포넌트 에서 id, class 지정해주기

손근영·2024년 9월 5일

React

목록 보기
2/10
export default function Section({ title, children, ...props }) {
  return (
    <section {...props}>
      <h2>{title}</h2>
      {children}
    </section>
  );
}

export default function Example() {
  const [selectedTopic, setSelectedTopic] = useState();

  function handleSelect(topic) {
    setSelectedTopic(topic);
  }
  return (
    <Section className="example" title="예시">
      <menu>
        <TabButton
          onSelect={() => handleSelect("props")}
          isSelected={selectedTopic === "props"}
        >
          데이터 전달
        </TabButton>
        <TabButton
          onSelect={() => handleSelect("component")}
          isSelected={selectedTopic === "component"}
        >
          재사용 컴포넌트
        </TabButton>
        <TabButton
          onSelect={() => handleSelect("styling")}
          isSelected={selectedTopic === "styling"}
        >
          동적 스타일링
        </TabButton>
      </menu>
      {selectedTopic}

      {selectedTopic === undefined ? (
        <p>주제를 선택해주세요.</p>
      ) : (
        <div style={{ backgroundColor: data[selectedTopic].backgroundColor }}>
          <h3>{data[selectedTopic].title}</h3>
          <p>{data[selectedTopic].content}</p>
          <pre>
            <code>{data[selectedTopic].code}</code>
          </pre>
        </div>
      )}
    </Section>
  );
}

Section 컴포넌트 의 class 속성을 줘야하는데,
원래 section 이라는 태그로 되어있을 때는

<section className="example">

라고 썼으면 됐는데,
컴포넌트로 변환하니 class가 적용이 안된다.
그럴땐 spread operator 를 사용하면된다.

Section.jsx 에서 Section 의 props 에다가 id , className 등 미리 내장되어 있는 속성들을 그냥 ...props 라고 적어놓고,

Section .jsx 안에서

<section {...props}>

로 해주면 됨.

0개의 댓글