Home > Mobile >  I can't add 1 day on MUI X Date picker on button press
I can't add 1 day on MUI X Date picker on button press

Time:10-21

I am currently trying to add 1 day to my date picker on button press but it instead goes to 01/01/1970 when I try to add 1 day to it! Same as when I try to subtract 1 to it

What I'm trying to achieve is this :

Here's an image of my Date picker DatePicker

Whenever I Click the ">" button it goes up by one day and when I click "<" button It goes down a day, I dont know if that's possible for MUI X Date pickers or should I try a different date picker?

Here is my code

import React, { useState } from "react";

import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import dayjs from "dayjs";
import TextField from "@mui/material/TextField";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";

function AddEntry(props) {
  const [datePicker, setDatePicker] = useState(dayjs(new Date()));

  const handleArrows = (e) => {
    if (e.target.innerText === ">") {
      setDatePicker(datePicker.$d   1);
      console.log("Next");
      console.log(datePicker);
      // YYYY/MM/DD
    } else {
      console.log("Prev");
      console.log(datePicker);
    }
  };

  return (
    <>
      <label className="date-label">Date:</label>
      <div className="date-field">
        <LocalizationProvider dateAdapter={AdapterDayjs}>
          <button
            className="arrow-btn"
            onClick={(e) => {
              handleArrows(e);
            }}
          >
            {"<"}
          </button>
          <DatePicker
            disableFuture
            openTo="day"
            views={["month", "day"]}
            value={datePicker}
            maxDate={new Date()}
            onChange={(newDate) => {
              setDatePicker(newDate);
            }}
            inputFormat="MM/DD/YYYY"
            renderInput={(params) => <TextField {...params} />}
          />
          <button
            className="arrow-btn"
            onClick={(e) => {
              handleArrows(e);
            }}
          >
            {">"}
          </button>
        </LocalizationProvider>
      </div>
    </>
  );
}
export default AddEntry;

CodePudding user response:

I found your handleArrows function really complex. You need to redo your handleArrows function completely. For working example I have used e.target.id insted of your innerText and also used day.js .add(1, "day") api for handling date change.

Feel free to inspire with my solution: https://codesandbox.io/s/exciting-cache-rjgtlk?file=/src/App.js (please, refresh codesandbox window, when there is a compile error)

Happy hacking!

  • Related