React에서 list 편하게 생성하기 (feat.map)

Heidi·2022년 5월 4일
0

React

목록 보기
4/8
post-thumbnail

list와 key

Javascript의 map 함수를 알아야 사용이 가능하다.

map 예시

const array1 = [1, 4, 9, 16];

const map1 = array1.map(x => x * 2);

console.log(map1);
expected output: Array [2, 8, 18, 32]

map은 기존 배열을 본인이 원하는 조건을 걸어 새로운 배열을 만든다.
리액트는 map을 component에 담아 보다 간편하게 리스트를 만들 수 있다.

참고

map 뿐 아니라, 배열 반복문 foreach, filter, reduce도 사용할 수 있지만
리액트에서는 보통 map을 활용한다.

  <script type="text/babel">

    //프론트에서 배열로 받아 배열을 반복하여 해당 객체내용을 추출하여

    class List extends React.Component {

      state = {
        board : [
          {id : 1, subject : 'heidi'},
          {id : 2, subject : 'heidi'},
          {id : 3, subject : 'heidi'},
          {id : 4, subject : 'heidi'},
        ] // DB통신하여 결과물을 받은 객체로 가정하여 진행
      }

      
      list = this.state.board.map( (value, key) => {
        return(
          <li key={key}>
            <span>{value.id}</span>
            <span> : </span>
            <span>{value.subject}</span>
          </li>
        )
      }) // 배열이 반환됨

      render(){
        return(
          <ul>
            {this.list}
          </ul>
        )
      }
    }

    class App extends React.Component {
      render(){
        return(
          <div>
            <List />
          </div>
        )
      }
    }

    ReactDOM.render(<App />, document.querySelector("#root"));
  </script>


위와 같이 결과물이 나온다.

profile
햇님쓰 개발일기장

0개의 댓글