느려도 한걸음씩

Props를 전달하는 여러가지 방법 본문

FE develop/React

Props를 전달하는 여러가지 방법

hoj0806 2024. 3. 27. 00:10

 



export const CORE_CONCEPTS = [
  {
    image: componentsImg,
    title: "Components",
    description:
      "The core UI building block - compose the user interface by combining multiple components.",
  },
  {
    image: jsxImg,
    title: "JSX",
    description:
      "Return (potentially dynamic) HTML(ish) code to define the actual markup that will be rendered.",
  },
  {
    image: propsImg,
    title: "Props",
    description:
      "Make components configurable (and therefore reusable) by passing input data to them.",
  },
  {
    image: stateImg,
    title: "State",
    description:
      "React-managed data which, when changed, causes the component to re-render & the UI to update.",
  },
];

 

이런 데이터가 있다고 쳐보자 

 

 <ul>
            {CORE_CONCEPTS.map((item, index) => {
              return <CoreConcept key={index} />;
            })}
   </ul>
 
 

 

CoreConcept 컴포넌트로 각각 요소들을 보내 props로 전달해야한다 

 

 

export default function CoreConcept() {
 

  return (
    <li>
      <img/>
      <h3></h3>
      <p></p>
    </li>
  );
}

 

 

 

 

 

 

1.가장 기본적인 방식

  <ul>
            {CORE_CONCEPTS.map((item, index) => {
              return (
                <CoreConcept
                  title={item.title}
                  description={item.description}
                  image={item.image}
                  key={item.index}
                />
              );
            })}
 </ul>


export default function CoreConcept(props) {
  return (
    <li>
      <img src={props.image} alt={props.title} />
      <h3>{props.title}</h3>
      <p>{props.description}</p>
    </li>
  );
}

 

props객체를 그대로 받아 받아올 프로퍼티를 점 표기법을 이용해 중괄호에 넣어준다

 

 

 

또는 props를 받는 컴포넌트에서 구조 분해할당을 이용해 

 

export default function CoreConcept({ title, description, image }) {
  return (
    <li>
      <img src={image} alt={title} />
      <h3>{title}</h3>
      <p>{description}</p>
    </li>
  );
}

 

이렇게 사용할 수도 있다

 

 

 

 

2. props를 객체로 그룹화해서 전달

 

 <ul>
            {CORE_CONCEPTS.map((item, index) => {
              return <CoreConcept {...CORE_CONCEPTS[index]} key={index} />;
            })}
 </ul>
 
export default function CoreConcept({ title, description, image }) {
  return (
    <li>
      <img src={image} alt={title} />
      <h3>{title}</h3>
      <p>{description}</p>
    </li>
  );
}

 

props를 사용할때 객체의 값을 다룬다면 반드시 객체에 있는 key의 이름을 그대로 써야한다 

 

 

또는 이렇게 사용할 수 도 있다

 

export default function CoreConcept({ ...concept }) {
  const { title, description, image } = concept;
  return (
    <li>
      <img src={image} alt={title} />
      <h3>{title}</h3>
      <p>{description}</p>
    </li>
  );
}