간단한 jsx 지식
return(
<div>
<div></div>
<div></div>
</div>
)
위 처럼 return문 안에있는 html을 사용할때는 최상위 태그는 반드시 하나여야 한다.
return(
<>
<div></div>
<div></div>
</>
)
이렇게 fragment 문법으로 빈 태그로 감싸줘도 된다.
그럼 이제 게시글 제목을 클릭하면 목록 아래에 게시글 상세화면 뜨도록 해보자.
상세페이지 만들기
일단 상세화면 디자인부터 하기.
// App.js
<div className="modal">
<h4>제목</h4>
<p>날짜</p>
<p>상세내용</p>
</div>
/* App.css */
.modal{
margin-top : 20px;
padding : 20px;
background : #eee;
text-align : left;
}
저 modal 태그 전체를 하나의 Component로 만들어 App Component의 자식으로 넣어주자. 리액트의 핵심 Component 을 사용해보는 것이다.
사실 App도 하나의 Component 였던것.
function App (){
return (
<div>
.
.
<Modal></Modal>
</div>
)
}
function Modal(){
return (
<div className="modal">
<h4>제목</h4>
<p>날짜</p>
<p>상세내용</p>
</div>
)
}
이렇게 해주면 된다. <Modal></Modal> 이게 방금 만든 Component를 적용한 모습.
Component 생성시 주의점
- Component 이름은 대문자로 시작해야한다.
- function App(){
return~
}
바깥에 만들어야한다.<Modal></Modal><Modal/>이렇게 두가지로 사용한다.- function Modal(){
return~
}
const Moal = ()=>{
return()
}
이렇게 두가지 함수 생성 방식에 따라 Component 생성 가능.
Component 만들면 좋은 html이란?
- 반복해서 나타나는 html 덩어리들
- 가변성이 있는 html 덩어리들
- 재사용 가능성이 있는 html 덩어리들
Component의 단점도 있다.
한 Component 안에 있는 변수나 state는 다른 Component에서 바로 사용불가능.
따라서 props라는 문법으로 하위 태그까지 전달해줘야 하는 번거로움이 있다.
리액트에서 동적인 UI 만드는 방법
- UI 부분 디자인 다 해놓기
- UI 현재 상태를 state로 저장하기
- state 따라서 UI가 어떻게 보일지 조건문으로 작성
1번은 아까 했으니 패스.
2번을 해보면
const [modal, setModal] = useState(false);
true이면 보여지고 false이면 보이지 않는다고 설정했다.
3번을 해보자.
function App (){
return (
<div>
.
.
{modal == true ? <Modal/> : ""}
</div>
)
}
이렇게 해주면 된다.
jsx 안에선 if 또는 for 를 사용할 수 없고 { } 안에서 삼항연산자를 사용하여 조건을 삽입한다.
글 제목을 누르면 modal 을 true 바꿔줘야 Modal Component가 보이겠지?
.
.
return (
<div className="App">
<div className="black-nav">
<div>My blog</div>
</div>
<div className="list">
<h4 onClick={()=>{
setModal(true);
}}>{posts[0].title}
</h4>
<p>{posts[0].date}</p>
<hr/>
</div>
</div>
)
제목 태그에 onClick 이벤트를 연결했다.
이제 제목 누르면 상세화면이 보인다.