Home > other >  Not able to write into textfield
Not able to write into textfield

Time:09-23

i'm quite new with react and i'm building a form with react-hook and useState to manage my datas after the submit.

I'm not able to use textfield as they are blocked. I think that i make some errors into value/onChange parameters but i don't know what type of error.

import React, { useState } from "react";

import {
  TextField,
  MenuItem,
  Typography,
  Checkbox,
  Divider,
  Button,
} from "@mui/material";
import { MdError } from "react-icons/md";
import { BsArrowRight } from "react-icons/bs";
import "../style/contactform.scss";

import { useForm } from "react-hook-form";

const initialState = {
  name: "",
  email: "",
};

const ContactForm = () => {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm();

  const [state, setState] = useState(initialState);
  const { name, email } = state;

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setState({ ...state, [name]: value });
  };

  const onSubmit = (e) => {
    e.preventDefault();
    console.log("form submit");
    setState(initialState);
  };

  return (
    <form className="contact-form" onSubmit={handleSubmit(onSubmit)}>
      <Typography variant="h4" className="form-title">
        Be the first.
      </Typography>

      <div className="form-component">
        <TextField
          id="standard-basic"
          label="Nome*"
          variant="standard"
          name="nome"
          value={name}
          onChange={handleInputChange}
          {...register("nome", {
            required: true,
          })}
        />

        {errors?.nome?.type === "required" && (
          <MdError className="form-validation-icon" />
        )}
      </div>

      <Divider className="form-hr" />

      <div className="form-component">
        <TextField
          id="standard-basic"
          label="Email*"
          variant="standard"
          name="email"
          value={email}
          onChange={handleInputChange}
          {...register("email", {
            required: true,
            pattern: {
              value:
                /^[a-zA-Z0-9.!#$%&’* /=?^_`{|}~-] @[a-zA-Z0-9-] (?:\.[a-zA-Z0-9-] )*$/,
            },
          })}
        />

        {errors?.email?.type === "required" && (
          <MdError className="form-validation-icon" />
        )}
        {errors?.email?.type === "pattern" && (
          <Typography variant="p" className="form-validation-email">
            Inserisci un indirizzo email valido.
          </Typography>
        )}
      </div>

      <Divider className="form-hr" />

      <Button className="form-submit" type="submit" variant="contained">
        <BsArrowRight />
      </Button>
    </form>
  );
};

export default ContactForm;

Textfields are completely block but initial state is actually working, do i miss something? Can you help me?

CodePudding user response:

To assign initial values using the useForm hook, you pass it under the defaultValues parameter passed to the hook like so:

const {
    register,
    handleSubmit,
    reset
    formState: { errors },
  } = useForm({
    defaultValues: initialState
  });

Then just pass the ...register name and email to the inputs. There is no need to assign values to them again:

<TextField
  id="standard-basic"
  label="Name*"
  variant="standard"
  name="name"
  {...register("name", {
    required: true,
  })}
/>

// for the email..
<TextField
  id="standard-basic"
  label="Email*"
  variant="standard"
  name="email"
  {...register("email", {
    required: true,
    pattern: {
      value: /^[a-zA-Z0-9.!#$%&’* /=?^_`{|}~-] @[a-zA-Z0-9-] (?:\.[a-zA-Z0-9-] )*$/,},
  })}
/>

If you'll notice, the values are off the text fields already and there's also no need for the handleInputChange function. The useForm hook takes care of that.

Edit: In addition to the onSubmit function, the handleSubmit from useForm passes a data object into the function like this:

const onSubmit = (data) => {
  console.log("form submitted", data);
  reset(); // this can be destructured of the `useForm` hook.
};

For more info check their documentation

  • Related