Home > front end >  React: Name not coming through onChange(), e.target.name is undefined on DatePicker
React: Name not coming through onChange(), e.target.name is undefined on DatePicker

Time:10-05

I'm using a building a MERN Stack application ("react": "^16.14.0") that has a form using DatePicker ("react-datepicker": "^4.2.1") to set a date range. Currently, the value for the date is being selected, but the name is coming through undefined. This is throwing a TypeError and crashing the application when a date is selected. How do I set the e.target.name to startDate and endDate?

TyperError

react-dom.development.js:327 
Uncaught TypeError: Cannot read properties of undefined (reading 'name') 
  at onChange (index.js:55)

formData

const [formData, setFormData] = useState({
  startDate: '',
  endDate: '',
})

const {
  startDate,
  endDate,
} = formData

DatePicker

<DatePicker
  isClearable
  filterDate={(d) => {return new Date() > d}}
  placeholderText="Select Start Date"
  dateFormat="MMMM yyyy"
  selected={startDate}
  selectsStart
  startDate={startDate}
  endDate={endDate}
  onChange={(date) => onChange({ name: startDate, value: date })}
/>

onChange Function

const onChange = (e) => {
  console.log(e) 
  setFormData({ ...formData, [e.target.name]: e.target.value })
}

Console.log()

name: undefined
value: Tue Aug 03 2021 00:00:00 GMT-0400 (Eastern Daylight Time)

CodePudding user response:

Reason why that happens is that you onChange is not receiving any event, thus the e.target is undefined. if you take a look here:

// Add the name explicitly as a string, cause you're trying to update a key by its name
onChange={(date) => onChange({ name: "startDate", value: date })}

The onChange is receiving and object with the name and value keys. so the onChange function should be like this:

const onChange = (item) => {
  console.log(item) 
  // should print something like { name: "startDate", value: "the date object" }
  setFormData({ ...formData, [item.name]: item.value })
}
  • Related