Login.tsx 2.16 KB
import React, { useCallback, useState } from "react";
import { Form, Input, Button, Checkbox, Layout } from "antd";
import { UserOutlined, LockOutlined } from "@ant-design/icons";
import { useHistory } from "react-router-dom";

import styles from "./Login.module.scss";

export type LoginProps = {
  login: (
    username: string,
    password: string,
    remember: boolean
  ) => Promise<void>;
};

export function Login({ login }: LoginProps) {
  const [error, setError] = useState<boolean>(false);
  const history = useHistory();

  const handleLogin = useCallback(
    async ({ username, password, remember }) => {
      setError(false);
      try {
        await login(username, password, remember);
        history.push("/");
      } catch {
        setError(true);
      }
    },
    [login, history]
  );

  return (
    <Layout className={styles.layout}>
      <Layout.Content className={styles.content}>
        <Form
          name="login"
          initialValues={{ remember: true }}
          onFinish={handleLogin}
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: "아이디를 입력하세요" }]}
            {...(error && {
              validateStatus: "error",
            })}
          >
            <Input prefix={<UserOutlined />} placeholder="아이디" />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: "Please input your Password!" }]}
            {...(error && {
              validateStatus: "error",
              help: "로그인에 실패했습니다",
            })}
          >
            <Input
              prefix={<LockOutlined />}
              type="password"
              placeholder="비밀번호"
            />
          </Form.Item>
          <Form.Item>
            <Form.Item name="remember" valuePropName="checked" noStyle>
              <Checkbox>자동 로그인</Checkbox>
            </Form.Item>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit">
              로그인
            </Button>
          </Form.Item>
        </Form>
      </Layout.Content>
    </Layout>
  );
}