MDB DatePicker useState React


Topic: MDB DatePicker useState React

Bridget Melvin pro premium asked 2 years ago

Expected behavior I want to use the value and onChange prop with MDBDatepicker with React's useState variables and custom change handler. How can I accomplish this?

Actual behavior I get an error in the dev tools: "Uncaught TypeError: Cannot read properties of undefined (reading 'value')"

Resources (screenshots, code snippets etc.)

Form snippet

<label htmlFor='investment-date'>Investment Date</label>
<MDBDatepicker 
    icon='fas fa-calendar'
    format='m/d/yyyy'
    value={userInput.enteredInvDate}
    onChange={invDateChangeHandler}
/>

useState snippet

  const [userInput, setUserInput] = useState({
    ...
    enteredInvDate: company.investmentDate,    // a string in format 'm/d/yyyy'
    ...
  })

Change Handler snippet

  const invDateChangeHandler = (event) => {
    setUserInput((prevState) => ({
      ...prevState,
      enteredInvDate: event.target.value
    }))
  }

Your onChange function should look this way:

         onChange={(date) => {
            setUserInput((prevState) => ({
              ...prevState,
              enteredInvDate: date,
            }));
          }}

Datepicker is not a normal input, so it does not return an event on change.


Bridget Melvin pro premium commented 2 years ago

I am using MDB React UI Kit v5.0.0 and still cannot use the value and onChange properties.

const investmentDateHandler = (date) => { setUserInput((prevState) => ({ ...prevState, // enteredInvestmentDate: event.target.value, enteredInvestmentDate: date, })); };

<DatePicker format="m/d/yyyy" value={userInput.enteredInvestmentDate} onChange={(date) => investmentDateHandler(date)} />


Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Answered

Specification of the issue
  • User: Pro
  • Premium support: Yes
  • Technology: MDB React
  • MDB Version: MDB5 4.1.0
  • Device: Surface Laptop Studio
  • Browser: Chrome
  • OS: Windows 11
  • Provided sample code: No
  • Provided link: No