Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}`);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading