Search code examples
javascriptreactjsreact-calendar

New to React; react-calendar props showing as undefined in separate function but work with anonymous function


    import logo from './logo.svg';
    import React, { useState } from 'react';
    import ReactDOM from 'react-dom/client';
    import './index.css';
    import reportWebVitals from './reportWebVitals';
    import Calendar from 'react-calendar';
    import 'react-calendar/dist/Calendar.css';
    import './App.css';
    
    function App() {
      const [date, setDate] = useState(new Date());
    
      return (
        <Calendar
          onChange={setDate}
          value={date}
          minDetail="month"
          onClickDay={(value, event) => {alert(`This is the value ${value}`)}}
          tileContent={tileContent}
          tileDisabled={tileDisabled}
          maxDate={new Date(Date.now() + (6.048e+8 * 2))}
          minDate={new Date(Date.now() - (6.048e+8 * 2))}
        />
      )
    }
    
    function onClickDay({ value, event }) {
      alert(`This is the value ${value}`);
    }
    
    function tileContent({ date, view }) {
      return 'My Content';
    }

    function tileDisabled({ date, view }) {
      if (view === 'month') {
        return date.getDay() === 6 || date.getDay() === 0;
      }
    }

    export default App;

Hi all. I'm new to React. I'm trying to alter the default calendar component from react-calendar. What I've noticed is that for the onClickDay={(value, event) => {alert(This is the value ${value})}} line, if I replace this line with onClickDay={onClickDay} to call the separate function, the alert that gets displayed shows that value is undefined. But value is defined when the function is used as an arrow function as shown below. What am I doing wrong?


Solution

  • onClickDay takes a function of type (value: Date, event: React.MouseEvent<HTMLButtonElement>) => void. The function you have defined separately takes an object with a value and event, rather than two params value and event.

    // rather than  ({ value, event }):
    function onClickDay(value, event) {
      alert(`This is the value ${value}`);
    }