How to get the first and last visible date in React Big Calendar? This will facilitate database queries to view events. I'm trying to call the onNavigate ()
function and get start
and end
using the moment
library, but both values areundefined
.
Update
I get the value of start. end only when I press the back, next arrows. How do you get these values automatically when the calendar appears?
class App extends Component {
constructor() {
super();
this.state = {
current_date: '',
events: [{
id: 0,
title: 'All Day Event very long title',
allDay: true,
start: new Date(2019, 3, 0),
end: new Date(2019, 3, 1),
},
{
id: 1,
title: 'Long Event',
start: new Date(2019, 3, 7),
end: new Date(2019, 3, 10),
}
]
};
}
onNavigate =(date, view) => {
let start, end;
if (view === 'month') {
start = moment(date).startOf('month').startOf('week')
console.log(start)
end = moment(date).endOf('month').endOf('week')
}
console.log(start, end);
return console.log({ start, end });
}
render() {
console.log(this.state.current_date)
return (
<div>
<Calendar
localizer={localizer}
events={this.state.events}
startAccessor="start"
endAccessor="end"
onNavigate={this.onNavigate()}
/>
</div>
);
}
}
You made a common mistake when using arrow functions inside react components. just simply by changing onNavigate={this.onNavigate()}
to onNavigate={this.onNavigate}
your problem will be solved. I will give you a simple example to find waht is happening here. If you simply want to pass a function to an onClick handler you can define your function and pass it to onClick
by three ways:
1- Define an arrow function and passing it:
class Example extends Component {
clickHandler=()=>{
console.log('I am clickHandler');
}
render() {
return (
<div onClick={this.clickHandler}>
Example
</div>
);
}
}
2- Define a common function and passing it:
class Example extends Component {
clickHandler(){
console.log('I am clickHandler');
}
render() {
return (
<div onClick={()=>this.clickHandler()}>
Example
</div>
);
}
}
3- Define a function and binding it (this is old and is not common any more in ES6):
class Example extends Component {
clickHandler(){
console.log('I am clickHandler');
}
render() {
return (
<div onClick={this.clickHandler.bind(this)}>
Example
</div>
);
}
}
I hope this is helpful for you.
You're getting undefined
because of this : onNavigate={this.onNavigate()}
This will cause this.onNavigate
to be called with ()
( No params ) and date
will be undefined
, therefore, start
and end
will be undefined
,
You're calling the function instead of passing it
You should pass this.onNavigate
either like :
onNavigate={this.onNavigate}
Or :
onNavigate={(date, view) => this.onNavigate(date, view)}
See : navigate to a specific date
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With