JSX 챕터에서 실습했던 코드를 한 번 살펴보겠습니다.
function App() {
const name = '라이캣!';
const someStyle = {backgroundColor:"black", color:"white"};
const today = new Date();
const year = today.getFullYear();
const month = today.getMonth()+1;
const date = today.getDate();
const hour = today.getHours();
const min = today.getMinutes();
const sec = today.getSeconds();
return (
<div>
<div>
<h1 style={someStyle}>안녕, {name} 1호</h1>
<h1>안녕, 라이캣 2호!</h1>
<div className="newClass"/>
</div>
<div style={{backgroundColor:"black", color:"white"}}>
<h1 style={{color:'red'}}>년 : {year}</h1>
<h1>월/일 : {month}/{date}</h1>
<h1>시간 : {hour}시 {min}분 {sec}초</h1>
</div>
</div>
);
}
export default App;
처음에 작성했던 코드와 비교하면 태그들이 많이 늘어났네요! 하지만 우리가 실제로 페이지를 만들게 된다면 return() 안에 있는 코드가 정말 많이 길어질 것입니다.
코드가 길어질수록 가독성도 떨어지겠죠? 지금부터 가독성을 높이고 유지보수를 쉽게 할 수 있는 방법을 소개하겠습니다.
<aside> 💡 h1이 문서에 5개입니다. h1은 문서 내 1개만 작성해야 하기 때문에 컴포넌트를 나눌 때에도 이러한 시맨틱 구조에 신경을 써야 합니다.
</aside>
return (
<div>
<Licat />{/* 라이켓 모음 */}
<Time />{/* 시간보여주기 */}
</div>
)
이렇게 묶은 것을 컴포넌트라고 합니다. 각 기능 또는 목적에 따라 분리하여 사용하면 매우 편리하겠죠?
먼저 어떻게 분리할지 살펴본 후 분리해 보도록 하겠습니다. 분리할 부분은 주석으로 표시하였습니다.
function App() {
const name = '라이캣!';
const someStyle = {backgroundColor:"black", color:"white"};
const today = new Date();
const year = today.getFullYear();
const month = today.getMonth()+1;
const date = today.getDate();
const hour = today.getHours();
const min = today.getMinutes();
const sec = today.getSeconds();
return (
<div>
{/* 여기부터 */}
<div>
<h1 style={someStyle}>안녕, {name} 1호</h1>{/* 이렇게하면 나옵니다. */}
<h1>안녕, 라이캣 2호!</h1>
<div className="newClass"/> {/* class대신 className=""로 진행! */}
</div>
{/* 여기까지 라이켓 */}
{/* 여기부터 */}
<div style={{backgroundColor:"black", color:"white"}}>
<h1 style={{color:'red'}}>년 : {year}</h1>
<h1>월/일 : {month}/{date}</h1>
<h1>시간 : {hour}시 {min}분 {sec}초</h1>
</div>
{/* 여기까지 시간! */}
</div>
);
}
export default App;
자, 아래와 같이 수정하였습니다. 실행시켜보면 이전과 동일한 화면이 표시됩니다.
function Licat(props) {
const name = '라이캣!';
const someStyle = {backgroundColor:"black", color:"white"};
return(
<div>
<h1 style={someStyle}>안녕, {name} 1호</h1>{/* 이렇게하면 나옵니다. */}
<h1>안녕, 라이캣 2호!</h1>
<div className="newClass"/> {/* class대신 className=""로 진행! */}
</div>
)
}
function Time(props) {
const today = new Date();
const year = today.getFullYear();
const month = today.getMonth()+1;
const date = today.getDate();
const hour = today.getHours();
const min = today.getMinutes();
const sec = today.getSeconds();
return(
<div style={{backgroundColor:"black", color:"white"}}>
<h1 style={{color:'red'}}>년 : {year}</h1>
<h1>월/일 : {month}/{date}</h1>
<h1>시간 : {hour}시 {min}분 {sec}초</h1>
</div>
)
}
function App() {
return (
<div>
<Licat />
<Time />
</div>
);
}
그런데 완성된 코드는 오히려 길어진 것을 볼 수 있습니다. 하지만 최상위 App()에서 바라보면 소스코드가 보다 보기 편하게 정리된 것을 볼 수 있습니다.
function App() {
return (
<div>
<Licat />
<Time />
</div>
);
}