React - props와 data destructuring

혜성·2022년 3월 17일
0
post-thumbnail

부모 컴포넌트로부터 자식 컴포넌트로 전달된 props 정보는 객체 형태를 가지고 있습니다.

전달된 객체의 이름은 props이고 전달된 각 정보는 전달한 props의 이름을 key로, state를 전달했다면 그 값을 value로 지니고 있습니다.

destructuring에 관한 경고문을 받은 코드

const UserComment = props => {
  return (
    <div className="comments">
      <span className="user-name">wecode</span>
      <span className="commnets-desc">{props.comment}</span>
    </div>
  );
};

댓글 달기 기능을 구현한 프로젝트에서 부모 컴포넌트로 부터 input에 입력한 값을 props를 통해 댓글을 표현하는 자식 컴포넌트로 전달했습니다.

자식 컴포넌트는 props를 인자로 전달받아 props.comment로 전달받은 props를 사용했습니다.

전달받은 props를 props. 으로 직접 사용하니 다음과 같은 경고문이 발생했습니다.

React는 props를 data destructuring 을 통해 사용하기를 권장하고 있다는 사실을 처음으로 해당 경고문을 통해 발견했습니다.

ES6 data destructuring

따라서 es6에 도입된 data destructuring에 대해 알아보고 이를 React에 적용해 보려합니다.

props = {
  firstName: "Moon",
  lastName: "Hyeseong",
  city: "seoul"
}

위 객체는 firstName, lastName, city 라는 프로퍼티를 전달받은 컴포넌트의 props 객체 모습일 것입니다.

es6 이전에는 다음과 같은 형태로 각각의 프로퍼티에 접근해야 했습니다.

onsole.log(person.firstName) // Moon
console.log(person.lastName) // Hyeseong
console.log(person.city) // seoul

하지만 es6가 도입된 후

const { firstName, lastName, city } = props;

///
const firstName = props.firstName
const lastName = props.lastName
const city = props.city

다음과 같이 Destructuring을 시켜준다면 props.을 사용하지 않고 프로퍼티에 접근이 바로 가능해 집니다.

전달받은 props를 data destructuring 해보자

그렇다면 이전에 data destructuring을 하지 않고 props를 전달한 컴포넌트의 코드를 변경해 봅시다.

//부모태그로부터 전달받은 props 객체
props = {
  comment: "input에 입력한 댓글의 내용"
}

부모태그로부터 전달받은 props 객체의 모습은 다음과 같을것입니다.

// UserComment Component
//#1
const UserComment = (props) => {
  let {comment} = props;
  return (
    <div className="comments">
      <span className="user-name">wecode</span>
      <span className="commnets-desc">{props.comment}</span>
    </div>
  );
};
//OR

//#2
const UserComment = ({comment}) => {
  return (
    <div className="comments">
      <span className="user-name">wecode</span>
      <span className="commnets-desc">{props.comment}</span>
    </div>
  );
};

그리고 props를 data destructuring을 통해 받도록 수정한 컴포넌트입니다.

  • 첫번째 코드처럼 let {comment} = props;전달받은 props를 변수형태로 data destructuring 해주는 방식도 가능하며

  • 두번째 코드처럼 인자로 전달받는 단계에서 props를 data destructuring 해주는 방식 두가지 모두 가능합니다.

이렇게 props를 data destructuring 해주며 사용할시 전달받은 props의 내용들을 직관적으로 사용할 수 있어 더욱 깔끔하고 가독성 좋은 코드가 될 수 있습니다.

만약 객체를 props로 전달하는 경우 역시 props의 요소로 전달받은 객체를 동시에 data destructuring 해줄 수 있어 자유롭게 사용하면 될것 같습니다.

추후 하나가 아닌 여러 props를 전달받는 경우 더욱 효과적으로 props를 활용할 수 있을것이라 생각합니다.

0개의 댓글