Search code examples
reactjsreact-calendar

How can I pass the selected date(value) from react calendar to another component?


I am trying to pass the selected date to a component that contains the booking component and reservation button. I need the selected date for the axios call. This is what the Booking component looks like:

function Booking() {
  const [value, onChange] = useState(new Date());
  const disabledDates = [
    new Date(2021, 8, 13),
    new Date(2021, 8, 16),
  ];
  console.log(value);
  
  return (
    <div className="App">
      <Calendar
          onChange={onChange}
          value={value}
          maxDetail="month"
          minDetail="month"
          tileDisabled={({date, view}) =>
          (view === 'month') && // Block day tiles only
          disabledDates.some(disabledDate =>
            (date.getFullYear() === disabledDate.getFullYear() &&
            date.getMonth() === disabledDate.getMonth() &&
            date.getDate() === disabledDate.getDate()) 
          )}
      />
    </div>
  );
}
export default Booking;

Solution

  • You can move the state to the outer component, and make it a prop of the Booking component.

    function Booking({value, setValue}) {
      
      const disabledDates = [
        new Date(2021, 8, 13),
        new Date(2021, 8, 16),
      ];
      console.log(value);
      
      return (
        <div className="App">
          <Calendar
              onChange={setValue}
              value={value}
              maxDetail="month"
              minDetail="month"
              tileDisabled={({date, view}) =>
              (view === 'month') && // Block day tiles only
              disabledDates.some(disabledDate =>
                (date.getFullYear() === disabledDate.getFullYear() &&
                date.getMonth() === disabledDate.getMonth() &&
                date.getDate() === disabledDate.getDate()) 
              )}
          />
        </div>
      );
    }
    export default Booking;
    

    and in your outer component do something like this:

    function OuterComponent() {
      const [value, setValue] = useState(new Date());
    
      ...whatever else it needs to do
      
      return (<Booking value={value} setValue={setValue}/>
              ...whatever else it needs to contain
              );
    }