Search code examples
reactjsreact-router-domreact-big-calendar

Is there a way to make the url changing when switching between the react-big-calendar views?


I'm trying to implement switching between the react-big-calendar views using react-router-dom. I know the calendar has its own routing, but this routing doesn't change URL, so users can't return to the previous view using arrows or gestures, or open a concrete view using a link. Is there a way to implement it?


Solution

  • In a controlled state scenario, where you control date with onNavigate and view with onView, you can use those methods to control routing and then update the state variables with your url routes change.

    const onNavigate = (newDate, newView = viewFromState) => {
      // convert the date to some url string to use
      history.push(`${routeBase}/${convertedDate}/${newView}`);
    };
    
    const onView = (newView) => {
      history.push(`${routeBase}/${convertedDateFromState}/${newView}`)
    };
    
      // at your component route, and this is seriously paraphrasing
      const params = useParams();
      // I'm using a reducer, since I often update multiple
      // bits of state simultaneously. I also, in the reducer,
      // remember to convert the 'date' to a true JS Date object
      // for RBC
      dispatch({type: 'PARAMS', params});
    

    The Calendar uses your new onNavigate and onView methods for controlling those state values, your methods update the url and maintain history (so you can go forward and back), your Router updates the actual state values for the Calendar, and you get your calendar control and your browser history all together.