I'm using https://reactdatepicker.com
I seem to be having an issue in restricting weekends as shown in the example.
I'm using class component and trying to implement this functional example from the docs:
Example from docs:
() => {
const [startDate, setStartDate] = useState(null);
const isWeekday = date => {
const day = getDay(date);
return day !== 0 && day !== 6;
};
return (
<DatePicker
selected={startDate}
onChange={date => setStartDate(date)}
filterDate={isWeekday}
placeholderText="Select a weekday"
/>
);
};
Here is what I tried: I created the isWeekday
function and passed it to the DatePicker
.
import React from 'react'
import DatePicker from 'react-datepicker'
import getDay from 'react-datepicker'
import 'react-datepicker/dist/react-datepicker.css'
const isWeekday = (date) => {
const day = getDay(date)
return day !== 0 && day !== 6
}
export class Random extends React.Component {
constructor(props) {
super(props)
this.state = {
settlementDate: new Date(),
}
}
render() {
<DatePicker
selected={this.state.settlementDate}
onChange={(date) => this.setState({ settlementDate: date })}
minDate={new Date()}
filterDate={isWeekday}
/>
}
}
But I get the following error:
TypeError: Cannot call a class as a function
How can I make a datepicker with weekends restricted?
You are getting error:
TypeError: Cannot call a class as a function
because you are calling class as a function after importing default member from react-datepicker
:
Incorrect:
import getDay from 'react-datepicker' // You imported default class as `getDay`
const day = getDay(date) // You tried to call the class
Note: getDay isn't supposed to come from react-datepicker
. It is a standard JS Date's method.
Correct:
import React, { Component } from 'react'
import DatePicker from 'react-datepicker'
class SelectWeekDay extends Component<any, any> {
constructor(props) {
super(props)
this.state = {
startDate: null,
}
}
isWeekday = (date: Date) => {
const day = date.getDay()
return day !== 0 && day !== 6
}
render() {
return (
<>
<DatePicker
selected={this.state.startDate}
onChange={(date) =>
this.setState({
startDate: date,
})
}
filterDate={this.isWeekday}
/>
</>
)
}
}