Duchere
Duchere

Reputation: 59

Get Undefined with defaultValues in my React-Hook-Form form

I'm working on a React hook form project and I have some defaultValues for my fields, But when I submit the form without changing my input value I get undefined instead of my defaultValues values, have you an ideas please how to resolve this ?

PS : I don't want to use defaultValues of useForm

The Date for example is undefined in this case

DEMO : https://codesandbox.io/embed/react-hook-form-watch-v7-forked-f09o8u?fontsize=14&hidenavigation=1&theme=dark

Upvotes: 1

Views: 1347

Answers (2)

Bruno Andrade
Bruno Andrade

Reputation: 1

You should use defaultValues anyway. Simply declare a constant above your useForm call.

Your datepicker default values receives moment() output. It does not look its a RHF problem, but a antd instead. Check out antd docs.

According to moment() calls with string and format arguments, it returns a casted string, in your sandbox returned a Moment prototype for me. I would check antd's Datepicker default Values allowed types...

By the way I suggest typescript with react-hook-form, as long the docs says the same

Upvotes: 0

Francesco Vattiato
Francesco Vattiato

Reputation: 488

import React, { useState } from "react";
import ReactDOM from "react-dom";
import { useForm, Controller } from "react-hook-form";
import { DatePicker } from "antd";
import moment from "moment";
import "antd/dist/antd.css";

import "./styles.css";

function App() {
  const dateFormat = "YYYY-MM-DD";

  const [defaultValues, setDefaultValues] = useState({
    "MyField": "MydefaultValues",
    "MyDate": moment("2015-06-06", dateFormat)
  });

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

  const onSubmit = (data) => {
    console.log(data);
  };


  return (
    <>
      <form onSubmit={handleSubmit(onSubmit)}>
        <input
          type="text"
          placeholder="{field}"
          name={"MyField"}
          maxLength={500}
          rows={5}
          readOnly
          {...register("MyField", {
            required: true
          })}
        />
        <br />
        <Controller 
          name="MyDate"
          control={control}
          render={({field}) => (
            <DatePicker
              {...field}
              readOnly
            />
          )}
        />
        {/* based on yes selection to display Age */}
        <input type="submit" />
      </form>
    </>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

I suggest you to use the default values from useForm, but in order to meet your dynamic form requirements I can tell you that you can use a react state in order to define the useForm hook.

Another suggest I would give to you is to use the Controller component when you're using some custom component in order to properly handle the properties of the component itself.

Upvotes: 0

Related Questions