[React tutorial] 배열 객체 렌더링하기 (입문)

2020. 11. 10. 15:22React

리액트를 사용하여, 아래와 같은 배열 객체를 브라우저에 렌더링 하는 법을 배워보자.

// Friends 배열
const Friends = [
  {
    key: 1,
    name: 'Lim',
    hobby: 'crossfit',
    info: 'busan',
    brand: 'nike'
  },
  {
    key: 2,
    name: 'Kim',
    hobby: 'soccer',
    info: 'ulsan',
    brand: 'UA'
  },
  {
    key: 3,
    name: 'Him',
    hobby: 'basketball',
    info: 'tokyo',
    brand: 'adidas'
  }
];

class App

  • 한줄 한줄 다 뜯어보자
import Reat, {Component, Fragment } from 'react'; // Component, Fragment는 추후에 사용해야하기에 미리 import

class App extends Component {
  render() {
    return (
      <Fragment>
        {Friends.map(person => (
          <Group
            name={person.name}
            hobby={person.hobby}
            info={person.info}
            brand={person.brand} />
        ))}
      </Fragment>
    );
  }
}
export default App;

App 클래스의 기본 골격

  • App은 클래스이기에 기본적으로 return 대신 render()를 필요로 한다.
  • 그리고 render() 내부에서 return()을 사용한다.
class App extends Component {
  render() {
    return ();
  }
}

jsx 문법은 시작과 끝의 경계를 명확히 해줘야 하는데, 아래 코드의 경우엔 로 구분을 지었다. 꼭 fragment가 아니더라도, div로 묶어 줄 수도 있다.

<Fragment>
        {Friends.map(person => (
          <Group
            name={person.name}
            hobby={person.hobby}
            info={person.info}
            brand={person.brand} />
        ))}
</Fragment>
  • Frieds 배열 객체를 map()함수로 순회(iter)한다 (배열 안의 원소를 하나하나 거친다는 뜻이다).
  • person 이란 변수는 임의로 정한 이름의 객체. Friends 배열의 원소들(key, name, hobby ...)을 한 번씩 담을 수 있는 그릇정도로 생각해보자.
  • '=' 이전의 변수(name, hobby, info, brand)는 이란 컴포넌트로 보낼 props(properties).
  • '=' 이후의 변수(person.name, person.hobby, person.info, person.brand)는 Friends 배열에서 가져온 값

위에서 작성한 Fragment는 class App의 return()에 의해 Group component로 전달된다.


class App에서 return한 Fragment는 Group component로 보내진다

  • function Group()에 { name, hobby, info, brand } (<= 이건 fragment 태그 내의 '='이후의 변수)라는 인자가 전달된다.
  • 결국 아래 코드에서 return한 내용이 브라우저에 보여진다.
  • class App과 마찬가지로 fragment나 div로 전체를 묶어주어야한다. 아래에선 div로 묶어줬다.
function Group({ name, hobby, info, brand }) {
  return (
    <div>
      <h1>name: {name}</h1>
      <h3>hobby: {hobby}</h3>
      <h3>hometown: {info}</h3>
      <h4>fav_brand: {brand}</h4>
    </div>
  );
}

 

* 결과