arqex / react-datetime

A lightweight but complete datetime picker react component.
1.99k stars 873 forks source link

How to determine what is the currently viewed month #810

Open jestanoff opened 2 years ago

jestanoff commented 2 years ago

I need to augment the date picker with certain events (like public holidays should be green etc.) and render these on the days view. I'm struggling to find out the current month and year rendered in the view. Same date that is on the navigation bar as <th class="rdtSwitch">November 2021</th>

I tried certain things:

The only workaround I found is highjacking renderDay callback and saving the dates it renders. However that is an anti-pattern as it updates the component state before it finishes its render. Even React is complaining about it "Cannot update a component ("SomeComponent") while rendering a different component"

I'm using v2 but that shouldn't matter as looking into v3 docs there is still nothing that can help achieve my goal.

jestanoff commented 2 years ago

I came with a simple solution, getting the .rdtSwitch textContent

const [{ navigated, viewMode }, setState] = useState({ navigated: 0 });

const onNavigate = () => setState(prevState => ({ ...prevState, navigated: prevState.navigated + 1 }));

const onViewMode = useCallback(localViewMode => {
    setState(prevState => ({ ...prevState, viewMode: localViewMode }));
  }, []);

useLayoutEffect(() => {
    if (datePickerRef.current) {
      const viewedDate = datePickersRef.current.querySelector('.rdtSwitch').textContent;
      const [date] = viewedDate.match(/\w{3,9} \d{4}/) ?? []; // matches 'May 2021', 'September 2025'

      if (date) {
         doSideEffects(date);
      }
    }
  }, [doSideEffects, navigated, viewMode]);

return (
  <ReactDatetime 
    {...otherProps}
    onNavigateBack={onNavigate}  
    onNavigateForward={onNavigate}
    onViewMode={onViewMode}
  />
);