[개인 포트폴리오] [클라이밍 커뮤니티 SNS] 2. 코드 분석 <create-account.js>

2024. 12. 20. 10:49웹개발 포트폴리오

728x90
반응형
import { createUserWithEmailAndPassword, updateProfile } from "firebase/auth";
import { auth } from "../firebase";
import { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { FirebaseError } from "firebase/app";
import GithubButton from "../component/github-btn";
import styled from "styled-components";

const Switcher = styled.p` 
    color: white;

    a {
        color: white;
        text-decoration: none;
    }

    a:hover {
        text-decoration: underline;
    }
`;

const Logo = styled.img`
    position: absolute;
    width: 25vw;
    top: 10vw;
    right:45vh;

    @media (max-width: 768px) {
    display: none;
  }
`;

const Wrapper = styled.div`
  color: white;
  margin-left: 5vw;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  position: relative; /* 콘텐츠가 배경 위에 위치하도록 설정 */
  z-index: 1;

    @media (max-width: 768px) {
    margin: 0 2vw;
  }
`;

const Background = styled.div`
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-image: url('/background.jpg');
  background-size: cover;
  background-position: center;
  filter: blur(1px); /* 배경만 흐림 효과 적용 */
  z-index: -1; /* 배경이 콘텐츠 뒤에 위치하도록 설정 */

      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5); /* 50% 어두운 효과 */
        z-index: 1;
    }
    
    /* Wrapper 내의 모든 컨텐츠는 오버레이 위에 위치 */
    & > * {
        position: relative;
        z-index: 2;
    }
`;


const Input = styled.input`
  padding: 10px;
  margin: 10px;
  width: 25vw;
  border: 1px solid #ccc;
  border-radius: 5px;

@media (max-width: 768px) {
    width: 70vw;
  }
`;

const Form = styled.form`
  display: flex;
  flex-direction: column;
  align-items: center;
`;

const Footer = styled.footer`
  display: flex;
  justify-content: center; /* 수평 중앙 정렬 */
  align-items: center; /* 수직 중앙 정렬 */
  bottom: 0;
  color: white;
  width: 100%; /* 전체 너비 */
  margin: 0; /* 마진 제거 */
  padding: 1em 0; /* 적당한 패딩 추가 */
`;

export default function CreateAccount() {
    const navigate = useNavigate();
    const [isLoading, setLoading] = useState(false);
    const [name, setName] = useState("");
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [error, setError] = useState("");

    const onChange = (e) => {
        const { name, value } = e.target;
        if (name === "email") {
            setEmail(value);
        } else if (name === "password") {
            setPassword(value);
        }
    };

    const onSubmit = async (e) => {
        e.preventDefault();
        setError("");
        if (email === "" || password === "") return;
        try {
            setLoading(true);
            const credentials = await createUserWithEmailAndPassword(auth, email, password);
            console.log(credentials.user);
            await updateProfile(credentials.user, { displayName: name });
            navigate("/");
        } catch (e) {
            console.error(e); // 콘솔로 에러를 출력해 디버깅
            if (e.code) {
              switch (e.code) {
                case "auth/email-already-in-use":
                  setError("이미 사용 중인 이메일입니다.");
                  break;
                case "auth/invalid-email":
                  setError("유효하지 않은 이메일 주소입니다.");
                  break;
                case "auth/weak-password":
                  setError("비밀번호가 너무 약합니다.");
                  break;
                default:
                  setError("계정 생성 중 오류가 발생했습니다. 다시 시도해 주세요.");
                  break;
              }
            } else {
              setError("알 수 없는 오류가 발생했습니다.");
            }
          } finally {
            setLoading(false);
        }
    };

    return (
        <>
        <Background />
        <Wrapper>
            <h1>첫 방문을 환영해요.</h1>
            <Form onSubmit={onSubmit}>
            <Input
            onChange={onChange}
            name="email"
            value={email}
            placeholder="이메일"
            type="email"
            required
            />
            <Input
            onChange={onChange}
            name="password"
            value={password}
            placeholder="패스워드"
            type="password"
            required
            />
                <Input type="submit" value={isLoading ? "로딩중..." : "계정 만들기"}   style={{
                    backgroundColor: isLoading ? "#9D7B6F" : "#9D7B6F",
                    cursor: isLoading ? "not-allowed" : "pointer",
                    color: "white",
                }}/>
            </Form>
            {error && <p style={{ color: "red" }}>{error}</p>}
            <Switcher>
                <Link to="/login"> 이미 계정이 있나요? </Link>
            </Switcher>
            <GithubButton />
        </Wrapper>
        <Logo src="/logo.png" alt="Logo" />
        <Footer>
            <p>&copy; 2024 Yoon yurim. All rights reserved.</p>
        </Footer>

        </>
    );
}
728x90
반응형