Home React 05. Lists and Keys
Post
Cancel

React 05. Lists and Keys

반복되는 객체 Rendering

Javascript의 Map() 함수를 활용하여 반복되는 렌더링 작업을 처리할 수 있다. Map() 함수는 Array 리스트를 받아 새로운 리스트를 반환하는 함수이다.

1
2
3
4
5
6
7
    const array1 = [1, 4, 9, 16];

    // pass a function to map
    const map1 = array1.map(x => x * 2);

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

React에서도 Map() 함수를 이용해서 반복되는 component를 렌더링 할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    function NumberList(props) {
        const numbers = props.numbers;
        const listItems = numbers.map((number) =>
            <li>{number}</li>
        );
        return (
            <ul>{listItems}</ul>
        );
    }

    const numbers = [1, 2, 3, 4, 5];
    ReactDOM.render(
        <NumberList numbers={numbers} />,
        document.getElementById('root')
    );

해당 코드를 실행시키면 Key값이 없다는 Warning이 뜬다. Key값은 list element를 생성할 때 각 element에 포함되어야 하는 특수한 속성이다.

Keys

Keys는 React itmes의 변화, 추가, 제거와 같은 상태변화를 식별하는 것을 도와준다. Keys는 Array 내부 요소에 주어진다.

Key를 선택하는 가장 좋은 방법은 Object property 중 고유 식별 ID를 사용하는 것이다.

1
2
3
4
5
   const todoItems = todos.map((todo) =>
        <li key={todo.id}>
            {todo.text}
        </li>
    ); 

만약 Object property에 식별을 위한 ID가 없을 경우, Map함수의 두 번째 인자로 index를 넣어주면 Key 값을 할당할 수 있다.

1
2
3
4
5
6
    const todoItems = todos.map((todo, index) =>
        // Only do this if items have no stable IDs
        <li key={index}>
            {todo.text}
        </li>
    );

하지만, 항목의 순서가 변경될 수 있는 경우는 index를 사용하지 않는 것이 좋다.

또한, Keys는 Siblings 사이에서 반드시 Unique한 값이여야 한다. 하지만 Globally unique할 필요는 없다.

This post is licensed under CC BY 4.0 by the author.