i Want to change this class component in function component:
import React from "react";
import "./styles.css";
import DayPicker, { DateUtils } from "react-day-picker";
import "react-day-picker/lib/style.css";
export default class App extends React.Component {
constructor(props) {
super(props);
this.handleDayClick = this.handleDayClick.bind(this);
this.state = {
selectedDays: []
};
}
handleDayClick(day, { selected }) {
const { selectedDays } = this.state;
if (selected) {
const selectedIndex = selectedDays.findIndex((selectedDay) =>
DateUtils.isSameDay(selectedDay, day)
);
selectedDays.splice(selectedIndex, 1);
} else {
selectedDays.push(day);
}
this.setState({ selectedDays });
}
render() {
return (
<div>
{console.log(this.state.selectedDays)}
<DayPicker
selectedDays={this.state.selectedDays}
onDayClick={this.handleDayClick}
/>
</div>
);
}
}
demo: https://codesandbox.io/s/agitated-chaum-0qss8?file=/src/App.js:0-944
I did this:
const [selectedDays, setSelectedDays] = useState([])
const handleDayClick = (day, {selected}) => {
if (selected) {
const selectedIndex = selectedDays.findIndex(selectedDay =>
DateUtils.isSameDay(selectedDay, day)
);
console.log('test',selectedDays);
selectedDays.splice(selectedIndex, 1);
} else {
// selectedDays.push(day)
setSelectedDays([...selectedDays,day]);
}
}
console.log(selectedDays);
return (
<div className="er">
<DayPicker
selectedDays={selectedDays}
onDayClick={handleDayClick}
/>
</div>
);
};
The issue: When i select 1 date the date becomes active, but when i click again on it it does not change back into un-active state? What is the problem and how to solve?