Skip to content

Commit

Permalink
fix(Android): Don't re-render in datetime mode (#465)
Browse files Browse the repository at this point in the history
Store current date in a ref instead of state to avoid re-rendering of the time picker. Solves #451
  • Loading branch information
mmazzarolo committed Aug 11, 2020
1 parent fcbf064 commit bcbf35a
Showing 1 changed file with 15 additions and 9 deletions.
24 changes: 15 additions & 9 deletions src/DateTimePickerModal.android.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
import React, { useEffect, useState, memo } from "react";
import React, { useEffect, useRef, useState, memo } from "react";
import PropTypes from "prop-types";
import DateTimePicker from "@react-native-community/datetimepicker";

// Memo workaround for https://github.com/react-native-community/datetimepicker/issues/54
const areEqual = (prevProps, nextProps) => {
return (
prevProps.isVisible === nextProps.isVisible &&
prevProps.date === nextProps.date
);
};

const DateTimePickerModal = memo(
({ date, mode, isVisible, onCancel, onConfirm, onHide, ...otherProps }) => {
const [currentDate, setCurrentDate] = useState(date);
const currentDateRef = useRef(date);
const [currentMode, setCurrentMode] = useState(null);

useEffect(() => {
Expand All @@ -27,12 +35,12 @@ const DateTimePickerModal = memo(
if (mode === "datetime") {
if (currentMode === "date") {
setCurrentMode("time");
setCurrentDate(new Date(date));
currentDateRef.current = new Date(date);
return;
} else if (currentMode === "time") {
const year = currentDate.getFullYear();
const month = currentDate.getMonth();
const day = currentDate.getDate();
const year = currentDateRef.current.getFullYear();
const month = currentDateRef.current.getMonth();
const day = currentDateRef.current.getDate();
const hours = date.getHours();
const minutes = date.getMinutes();
nextDate = new Date(year, month, day, hours, minutes);
Expand All @@ -51,9 +59,7 @@ const DateTimePickerModal = memo(
/>
);
},
(prevProps, nextProps) =>
prevProps.isVisible === nextProps.isVisible &&
prevProps.date === nextProps.date
areEqual
);

DateTimePickerModal.propTypes = {
Expand Down

0 comments on commit bcbf35a

Please sign in to comment.