Skip to content
Snippets Groups Projects
contactForm.jsx 2.73 KiB
Newer Older
import { useState } from "react";

import { useTranslation } from "next-i18next";

import axios from "axios";

import {
  Alert,
  Button,
  Checkbox,
  Grid,
  Space,
  Textarea,
  TextInput,
} from "@mantine/core";
import { showNotification } from "@mantine/notifications";

export default function ContactForm() {
  const { t } = useTranslation("common");

  const [name, setName] = useState("");
  const [mail, setMail] = useState("");
  const [message, setMessage] = useState("");
  const [human, setHuman] = useState(false);
  const [robot, setRobot] = useState(false);

  const handleSubmit = async () => {
    if (!validate()) {
      showNotification({
        title: t("formIncomplete"),
        message: t("formIncompleteText"),
        color: "red",
      });
      return;
    }

    const response = await axios.post("/api/contact", {
      name: name,
      mail: mail,
      message: message,
      human: human,
      robot: robot,
    });

    if (response.data.message == "mailSuccess") {
      showNotification({
        title: t("mailSuccess"),
        message: t("mailSuccessText"),
        color: "green",
      });
    } else {
      showNotification({
        title: t("mailFailure"),
        message: t("mailFailureText"),
        color: "red",
      });
    }
  };

  const validate = () => {
    if (name == "") return false;
    if (mail == "") return false;
    if (message == "") return false;
    return true;
  };

  return (
    <>
      <Grid>
        <Grid.Col xs={12} sm={6}>
          <TextInput
            value={name}
            onChange={(e) => setName(e.target.value)}
            label={t("name")}
            withAsterisk
            placeholder="Maxime Musterfrau"
          />
        </Grid.Col>
        <Grid.Col xs={12} sm={6}>
          <TextInput
            value={mail}
            onChange={(e) => setMail(e.target.value)}
            label={t("mail")}
            withAsterisk
            placeholder="maxmu@student.ethz.ch"
          />
        </Grid.Col>
        <Grid.Col xs={12}>
          <Textarea
            value={message}
            onChange={(e) => setMessage(e.target.value)}
            label={t("message")}
            withAsterisk
            minRows={5}
          />
        </Grid.Col>
        <Grid.Col xs={12}>
          <Checkbox
            value={human}
            onChange={() => setHuman(!human)}
            label={t("human")}
          />
          <Space h="xs" />
          <Checkbox
            value={robot}
            onChange={() => setRobot(!robot)}
            label={t("robot")}
          />
        </Grid.Col>
        <Grid.Col xs={12}>
          <Button onClick={handleSubmit} variant="contained">
            {t("submit")}
          </Button>
        </Grid.Col>
      </Grid>
    </>
  );
}