I have made 2 buttons and one input field. Buttons (+/-) are to increment and decrement the counter. Initially the input field contents the date i.e data.available_slots[0].date
When I increment by clicking on + button the date changes dynamically from Wed, Dec 06 to Thur, Dec07 to Fri, Dec08 and so on to last date i.e Wed, Dec13.
The length of JSONdata is 7 i.e data.available_slots[0].date to data.available_slots[6].date so when the counter reaches 6 it should not increment further and if counter gets decremented then it should not go below 0.
But now when the counter(index) gets out of the bound it displays error (see screenshot)
See various screenshots which on click buttons display various dates in input field https://i.sstatic.net/xOvWO.jpg
datepicker.js:
import React, { Component } from 'react';
import data from './data';
import './datepicker.css';
class DatePicker extends Component {
constructor(props){
super(props);
this.state = {
counter:0
};
}
increment(){
this.setState({
counter: this.state.counter + 1
});
}
decrement(){
if(this.state.counter > 0){
this.setState(prevState => ({counter: prevState.counter-1}))
}
}
render() {
return (
<div>
<div id="center">
<label for="name">Pick a Date </label>
<p></p>
<button type="button" className="btn btn-success" id="plus" onClick={this.increment.bind(this)}>+</button>
<input type="text" id="date" value={data.available_slots[this.state.counter].date}/>
<button type="button" className="btn btn-danger" id="minus" onClick={this.decrement.bind(this)}>-</button>
</div>
</div>
);
}
}
export default DatePicker;
data.js:
const data = {
"template_type": "slot_picker",
"selection_color": "#000000",
"secondary_color": "#808080",
"title": "Available Slots for Dr. Sumit",
"available_slots": [
{
"date": "Wed, Dec 06",
"date_slots": [
]
},
{
"date": "Thu, Dec 07",
"date_slots": [
]
},
{
"date": "Fri, Dec 08",
"date_slots": [
]
},
{
"date": "Sat, Dec 09",
"date_slots": [
]
},
{
"date": "Today",
"date_slots": [
{
"hour": "8",
"hour_slots": [
{
"08:10 AM": "slotId001"
},
{
"08:50 AM": "slotId005"
}
]
},
{
"hour": "3",
"hour_slots": [
{
"03:00 PM": "slotId005"
},
{
"03:30 PM": "slotId007"
}
]
}
]
},
{
"date": "Tomorrow",
"date_slots": [
]
},
{
"date": "Wed, Dec 13",
"date_slots": [
{
"hour": "4",
"hour_slots": [
{
"04:30 PM": "slotId105"
},
{
"04:50 PM": "slotId106"
}
]
},
{
"hour": "5",
"hour_slots": [
{
"05:30 PM": "slotId202"
},
{
"05:45 PM": "slotId208"
}
]
}
]
}
]
};
export default data;
data.available_slots[0].datetodata.available_slots[6]so when the counter reaches 6 it should not increment further and if counter gets decremented then it should not go below 0 how to handle this.data.available_slots[0].datetodata.available_slots[6].dateso when the counter reaches 6 it should not increment further and if counter gets decremented then it should not go below 0 how to handle this