컴포넌트에 Props 전달하기

Sally·2026년 2월 10일

React 공식문서

목록 보기
4/11

props

  • props: JSX 태그에 전달하는 정보.
function Avatar() {
  return (
    <img
      className="avatar"
      src="https://i.imgur.com/1bX5QH6.jpg"
      alt="Lin Lanying"
      width={100}
      height={100}
    />
  );
}

export default function Profile() {
  return (
    <Avatar />
  );
}
  • className, src, width, alt 등은 <img> 태그에 전달할 수 있다

컴포넌트에 props 전달하기

1. 자식 컴포넌트에 props 전달하기

export default function Profile() {
  return (
    <Avatar
      person={{ name: 'Lin Lanying', imageId: '1bX5QH6' }}
      size={100}
    />
  );
}
  • person(객체)와 size(숫자) 전달함

2. 자식 컴포넌트 내부에서 props 읽기

function Avatar({ person, size }) {
  // person과 size는 이곳에서 사용가능합니다.
}
import { getImageUrl } from './utils.js';

function Avatar({ person, size }) {
  return (
    <img
      className="avatar"
      src={getImageUrl(person)}
      alt={person.name}
      width={size}
      height={size}
    />
  );
}

export default function Profile() {
  return (
    <div>
      <Avatar
        size={100}
        person={{
          name: 'Katsuko Saruhashi',
          imageId: 'YfeOqp2'
        }}
      />
      <Avatar
        size={80}
        person={{
          name: 'Aklilu Lemma',
          imageId: 'OKS67lh'
        }}
      />
      <Avatar
        size={100}
        person={{
          name: 'Lin Lanying',
          imageId: '1bX5QH6'
        }}
      />
    </div>
  );
}
  • props를 사용하면 부모 컴포넌트와 자식 컴포넌트를 독립적으로 생각할 수 있다. Avatar가 props를 어떻게 생각하는지 생각할 필요 없이 Profile의 person 또는 size props를 변경할 수 있다.
  • props는 함수의 매개변수처럼 생각하면 된다.

props는 부모 컴포넌트가 자식 컴포넌트에게 내려주는 값(데이터) 이다.

  • 읽기 전용
  • 부모 -> 자식 (O) // 자식 -> 부모 (X)
 function Avatar({ person, size = 100 }) {
  // ...
}
  • 변수 바로 뒤에 = 과 함께 기본값을 넣어 prop에 기본값을 지정할 수 있다.

JSX spread 문법으로 props 전달하기

function Profile({ person, size, isSepia, thickBorder }) {
  return (
    <div className="card">
      <Avatar
        person={person}
        size={size}
        isSepia={isSepia}
        thickBorder={thickBorder}
      />
    </div>
  );
}
  • 전달되는 props가 반복적일 때 간결한 spread 문법을 사용하여 코드를 간결하게 작성할 수 있다
function Profile(props) {
  return (
    <div className="card">
      <Avatar {...props} />
    </div>
  );
}
  • props 변경을 시도해서는 안된다. 선택한 색을 변경하는 등 사용자 입력에 반응해야 하는 경우에는 State를 사용해야한다.
profile
sally

0개의 댓글