Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 831
Tom Avatar asked Oct 28 '25 07:10

Tom


1 Answers

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.

like image 88
Tholle Avatar answered Oct 31 '25 01:10

Tholle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!