# 동적으로 생성된 태그에 이벤트 추가

  1. 컴포넌트의 props 중 onChangeMode 함수의 첫 번째 파라미터로 id 값 받음
  2. 컴포넌트 생성 부분에서 onChangeMode 를 호출할 때 id 값 전달
function Header(props){
  console.log("props : " , props, props.title)
  return <header>
    <h1><a href='/' onClick={(event)=>{
      event.preventDefault(); // 리로드 방지
      props.onChangeMode(); // Header 태그에 작성한 이벤트 호출
    }}>{props.title}</a></h1>
</header>
}

function Nav(props){
  const lis = []
  for(let i=0; i<props.topics.length; i++){
    let t = props.topics[i];
    lis.push(<li key={t.id}>
      <a id={t.id} href={'/read/'+t.id} onClick={event=>{
        event.preventDefault(); // 리로드 방지
        props.onChangeMode(event.target.id);  // Nav 태그에 작성한 이벤트 호출
        // event.target : 이벤트를 유발시킨 태그 == a 태그
      }}>{t.title}</a>
      </li>)
  }
  return <nav>
    <ol>
      {lis}
    </ol>
  </nav>
}

function Article(props){
  return <article>
    <h2>{props.title}</h2>
    {props.body}
  </article>
}

function App() {
  const topics = [
    {id:1, title:'html', body:'html is ...'},
    {id:2, title:'css', body:'css is ...'},
    {id:3, title:'javascript', body:'javascript is ...'},
  ]
  return (
    <div>
      <Header title="WEB" onChangeMode={()=>{
        alert('Header');
      }}></Header>
      <Nav topics = {topics} onChangeMode={(id)=>{
        alert(id);
      }}></Nav>
      <Article title="Welcome" body="Hello, WEB"></Article>
    </div>
  );
}

출처 : 생활 코딩 - https://youtu.be/AoMv0SIjZL8