How to set react-datepicker value for each text-field in Reactjs?

Viewed 35

import React, { useState } from "react";
import "./styles.css";

import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";

export default function MyComponent() {
  const [date, setDate] = useState(new Date());
  const handleChange = (date) => setDate(date);

  return <DatePicker selected={date} onChange={handleChange} />;
}

Here is my working codesandbox:- https://codesandbox.io/s/basic-datepicker-forked-4zyzv4?file=/src/MyComponent.js

Here is a small bug in my code. For example, Assume i have two datepickers one after another, when i try to select date from one datepicker, other datepicker also taking the same value.?

What exactly wrong with my code? For handleChange event, Do i need to take unique id for each? Can you please suggest what's wrong with my code.

1 Answers

I use a custom date picker component that I'm using in 12+ fields in an app, i'm using the name attribute for uniqueness.

<CustomDatePicker label="Start Date" name="start_date" disabled={false} /> 

Here is a gist of the component, it's using a store, but the onChange handler in the component may be helpful.

Update: Without using a custom component, I forked your codesandbox and updated the onChange handler to create a working demo with 2 datepicker fields.

  1. Change the date variable used to an object to support multiple values, example:

    const [dates, setDate] = useState({ sdate: new Date(), edate: "" });

  2. Modify the onChange handler in the field to identify the name attribute:

    onChange={handleChange.bind(this, "sdate")}

  3. Finally, update the handleChange function to support variables, and any number of date fields:

    const handleChange = (name, value) => { console.log(name, value); setDate((prev) => ({ ...prev, [name]: value })); };

Related