Tom
Tom

Reputation: 203

How to use material-ui-pickers's date picker with ReactJS's State Hook and pass date to the parent component?

I am trying to use material-ui-pickers's date picker, where example demos are written using State Hooks. I would like to get the date's value as a callback to the parent component. This is the child component:

import React, { Component } from 'react';
import { Fragment, useState } from "react";
import { DatePicker, InlineDatePicker } from "material-ui-pickers";

function YearMonthPicker(props) {
const [selectedDate, handleDateChange] = useState("2013-01-01");

  return (
        <div className="picker">
          <DatePicker
            openTo="year"
            views={["year", "month"]}
            label="Year and Month"
            helperText="With min and max"
            minDate={new Date("2011-01-01")}
            maxDate={new Date("2018-12-01")}
            value={selectedDate}
            onChange={handleDateChange}
          />
        </div>
  );
}

export default YearMonthPicker;

On "onChange", the function modifies its "selectedDate" state.

In my parent component, I defined the function:

handleChangeTo = e => {
    this.setState({ dateTo: e.target.value });
};

And, in the render method, I am trying to call it as such:

<YearMonthPicker handleChangeTo={this.handleChangeTo} />

As I understand it, If I change the function of "onChange" to props.handleChangeTo, then the child component's state will not be updated upon change. What's the right way to pass the date to the parent component?

Upvotes: 4

Views: 11221

Answers (1)

Tholle
Tholle

Reputation: 112777

Instead of using handleDataChange directly as the handler for onChange you can create a new function that calls handleDataChange and handleChangeTo from the props. handleChangeTo would then get the value directly, and not an event.

Example

function YearMonthPicker({ handleChangeTo }) {
  const [selectedDate, handleDateChange] = useState("2013-01-01");

  return (
    <div className="picker">
      <DatePicker
        openTo="year"
        views={["year", "month"]}
        label="Year and Month"
        helperText="With min and max"
        minDate={new Date("2011-01-01")}
        maxDate={new Date("2018-12-01")}
        value={selectedDate}
        onChange={val => {
          handleDateChange(val);
          handleChangeTo(val);
        }}
      />
    </div>
  );
}

Alternatively you could keep this state in the parent component and pass it down as props to YearMonthPicker and not have any component state in the child at all.

Upvotes: 5

Related Questions