简体   繁体   中英

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?

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}})}
/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM