List & Keys

hey hey·2021년 12월 7일
0

React 자료

목록 보기
6/18
post-thumbnail

List

map 함수를 이용해서 여러개 출력

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'));

keys

  • map 안에 있는 element는 key 가 필요하다.
  • key는 props로 전달되지 않는다 → 따로 id라고 보내야한다
  • 고유한 값
const listItems = numbers.map((**number**)=> 
		<li **key={number.toString()**}>{number}</li>);

id가 존재한다면?
cosnt todoItems = todos.map((todo)=>
	<li **key={todo.id}**> {todo.text}</li>);

id가 존재 안한다면? index 사용 (권유 안함)
cosnt todoItems = todos.map((todo,index)=> 
	<li **key={index}**> {todo.text}</li>);

⭐ List를 묶어서 ListItem 을 만들 때는 Listitem에 key를 줘야한다.

출석부

class AttendanceBook extends React.Component{
  constructor(props){
    super(props);

    this.state = {
      students:[
        {name:'Mike'},{name:'hommy'},{name:'jake'},{name:'susan'},
				{name:'yoshi'},{name:'mario'},{name:'luige'},{name:'koopa'},]
    }
  }
  render(){
    var students = this.state.students
    return (
      <ul>
        {students.map((student,index)=>
        <li **key={index**} >{student.name}</li>)}
      </ul>
    ) 
  }
}
export default AttendanceBook
profile
FE - devp

0개의 댓글