8-1. Key
- 배열 등을 이용하여 반복적인 컴포넌트 랜더링 하는 방법
- key
- 리액트에서 key는 컴포넌트의 배열 랜더링 시 어떤 요소에 변동이 있는지 알아보기 위한 식별자 역할
- key가 존재하지 않을 때는 가상 돔과 원본돔 비교 과정에서 리스트를 순차적으로 다 비교하지만, key가 존재하면 어떤 변화가 일어났는지 더 빠르게 감지 가능
- 인덱스를 사용하여 키값을 설정하는 것은 옳지 못한 방식
- 인덱스는 요소에 변화가 생기더라도 항목의 순서에 따라 재부여 되기 때문에 요소 식별 불가
- 일반적으로 DB에서 조회한 데이터인 경우 pk 컬럼 값을 key로 설정
const names = ['홍길동', '유관순', '윤봉길', '이순신', '임꺽정'];
function Items({ names }){
return(
<ul>
{ names.map((name, index) => <li key={index}>{name}</li>)}
</ul>
);
}
ReactDOM.createRoot(document.getElementById('root')).render(
(<Items names={names}/>)
);
8-2. Sample
const {useState} = React;
function App(){
const [names, setNames] = useState([
{id : 1, name : '홍길동'},
{id : 2, name : '유관순'},
{id : 3, name : '이순신'}
]);
const [inputText, setInputText] = useState('');
const [nextId, setNextId] = useState(4);
const onChangeHandler = e => setInputText(e.target.value);
const onClickHandler = () => {
const changedNames = names.concat({
id : nextId,
name : inputText
});
setNextId(nextId + 1);
setNames(changedNames);
setInputText('');
};
const onRemove = id => {
const changedNames = names.filter(item => item.id !== id);
setNames(changedNames);
}
const nameList = names.map(item => <li key={item.id}
onDoubleClick={ () => onRemove(item.id)}>
{item.name}
</li>);
return (
<>
<input value={inputText} onChange={onChangeHandler}/>
<button onClick={onClickHandler}>추가</button>
<ul>{nameList}</ul>
</>
)
}
ReactDOM.createRoot(document.getElementById('root')).render(<App/>);