user3174311
user3174311

Reputation: 2003

How to use date-picker in a react component using hooks

I have a component with a form that should display a date picker

const MyComponent = () => {
  const [formData, setFormData] = useState({
    dateFrom: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
    dateTo: new Date()
  });

  const handleOnChange = e => {
    setFormData({...formData, [e.target.name]: e.target.value});
  };

  return (
    <DatePicker
      selected={formData.dateFrom}
      name="dateFrom"
      dateFormat="MMMM d, yyyy"
      onChange={e => handleOnChange(e)}
      />
  );
};

What I need to do is to save the new date in the state, and get it back to update the component useing its selected property.

the handleOnChange method works for other form controls, not for the date picker, the error I am getting says :

Cannot read property 'name' of undefined

Any suggestion?

Upvotes: 2

Views: 699

Answers (1)

Taki
Taki

Reputation: 17664

the callback of onChange on the <DatePicker /> will have the value as first param, not the event, you can pass a similar Object to handleOnChange to keep it generic :

<DatePicker
  selected={formData.dateFrom}
  name="dateFrom"
  dateFormat="MMMM d, yyyy"
  onChange={value => handleOnChange({target : { name: "dateForm", value}})}
/>

Upvotes: 4

Related Questions