이 코드는 React에서 사용자 등록(가입) 및 사용자 수정 페이지를 처리하는 폼 컴포넌트의 예시입니다.
useLocation 훅을 사용하여 현재 페이지의 경로(/edit인지 아닌지)를 확인하고, 경로에 따라 동적으로 폼의 텍스트와 동작을 변경하는 방식입니다.
코드의 각 부분을 자세히 설명하겠습니다.
const UserForm = () => {
// 현재 URL 경로를 가져오는 useLocation 훅을 호출
const location = useLocation();
// 현재 경로가 '/edit'인지 확인
const isEditPage = location.pathname === "/edit";
// 폼 제출 시 호출되는 함수
const handleSubmit = (e) => {
e.preventDefault(); // 폼이 제출되었을 때 페이지 새로고침을 막음
// 현재 페이지가 수정 페이지인지 가입 페이지인지 확인하고, 콘솔에 해당 메시지를 출력
console.log(isEditPage ? "Edit submitted" : "Signup submitted");
};
return (
<div>
{/* 조건에 따라 타이틀을 다르게 렌더링 */}
<h1>{isEditPage ? "Edit Your Profile" : "Welcome! Sign Up Below"}</h1>
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="username">Username</label>
<input id="username" name="username" type="text" required />
</div>
<div>
<label htmlFor="email">Email</label>
<input id="email" name="email" type="email" required />
</div>
{/* 조건에 따라 버튼 텍스트를 다르게 렌더링 */}
<button type="submit">
{isEditPage ? "Save Changes" : "Sign Up"}
</button>
</form>
</div>
);
};
useLocation 훅:
const location = useLocation();
useLocation은 React Router에서 제공하는 훅으로, 현재 URL 경로를 반환합니다. 이 훅을 사용하면 페이지가 이동할 때마다 URL 정보를 쉽게 추적할 수 있습니다.location.pathname은 현재 페이지의 경로를 나타내며, 예를 들어 현재 URL이 http://localhost:3000/edit이라면, location.pathname은 "/edit"이 됩니다.isEditPage 변수:
const isEditPage = location.pathname === "/edit";
isEditPage는 현재 경로가 "/edit"인지 여부를 확인하는 변수입니다.location.pathname이 "/edit"이면 isEditPage는 true가 되고, 그렇지 않으면 false가 됩니다. 이 값을 통해 페이지가 수정 페이지인지 가입 페이지인지를 구분할 수 있습니다.handleSubmit 함수:
const handleSubmit = (e) => {
e.preventDefault(); // 폼 제출 시 페이지 새로고침을 막음
console.log(isEditPage ? "Edit submitted" : "Signup submitted");
};
e.preventDefault()는 기본 폼 제출 동작(페이지 새로고침)을 막고, 대신 console.log를 출력합니다.console.log(isEditPage ? "Edit submitted" : "Signup submitted")는 isEditPage의 값에 따라 다른 메시지를 출력합니다. 즉, 수정 페이지에서는 "Edit submitted", 가입 페이지에서는 "Signup submitted"을 출력합니다.조건부 렌더링 (타이틀 및 버튼 텍스트):
<h1>{isEditPage ? "Edit Your Profile" : "Welcome! Sign Up Below"}</h1>
<button type="submit">
{isEditPage ? "Save Changes" : "Sign Up"}
</button>
h1 태그와 button의 텍스트는 isEditPage 값에 따라 다르게 렌더링됩니다.isEditPage가 true일 때는 "Edit Your Profile"과 "Save Changes"가 표시되고, false일 때는 "Welcome! Sign Up Below"와 "Sign Up"이 표시됩니다.useLocation을 사용하여 현재 페이지의 경로를 추적하고, 그 경로가 /edit인지 여부를 isEditPage로 판별합니다.handleSubmit 함수에서 처리합니다.이와 같은 방식으로 하나의 컴포넌트를 재사용하면서도 페이지마다 다른 UI와 동작을 제공할 수 있습니다.