관리 메뉴

Silver Library (Archived)

react datepicker and useForm with controller. 본문

카테고리 없음

react datepicker and useForm with controller.

Chesed Kim 2023. 3. 2. 22:53
반응형
import React, { useState, useEffect } from "react";
import { useForm, Controller } from "react-hook-form";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import axios from "axios";

function App() {
  const [loadedDate, setLoadedDate] = useState(new Date());
  const { control, handleSubmit } = useForm();

  useEffect(() => {
    // Fetch data from API server and set loadedDate state
    axios
      .get("https://api.example.com/date")
      .then((response) => {
        setLoadedDate(new Date(response.data));
      })
      .catch((error) => {
        console.log(error);
      });
  }, []);

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

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label>Date:</label>
      <Controller
        name="date"
        control={control}
        defaultValue={loadedDate}
        render={({ field: { onChange, value } }) => (
          <DatePicker
            selected={value}
            onChange={(date) => {
              onChange(date);
              setLoadedDate(date);
            }}
            dateFormat="yyyy/MM/dd"
          />
        )}
      />
      <button type="submit">Submit</button>
    </form>
  );
}

export default App;

In this code, we use the useState hook to create a loadedDate state variable that will initially be set to the value obtained from the API server. We then use the useEffect hook to fetch the date from the API server and set the loadedDate state variable when the component mounts.

 

We use the useForm hook from react-hook-form to create a form that will handle the submission of the date value. We also use the Controller component from react-hook-form to integrate the DatePicker component with the form. We set the default value of the Controller to be the loadedDate state variable.

 

In the render function of the Controller, we create the DatePicker component and pass in the value and onChange props from the Controller as selected and onChange props for the DatePicker. We also set the dateFormat prop to "yyyy/MM/dd" to display the date in the desired format.

 

In the onChange function for the DatePicker, we call both the onChange function passed in from the Controller and the setLoadedDate function to update both the input and the DatePicker with the selected date value.

 

Finally, we add a submit button to the form and a handleSubmit function to handle the form submission. When the form is submitted, the onSubmit function will be called with the selected date value.