Hope you're all doing good guys!
I've been working on a calendar challenge in ReactJS and am facing an issue I really can't understand, I'm fetching days from a local API where I'm using an if Statement where if the current day of the month equals the day in the JSON file or less than that number then return an enabled button, else return disabled.
Here is the issue I'm facing: The days from 3 to 9 are disabled but I want them to be enabled as I wish for the user to be able to click on them. The days counting after the 25th to the 31st are disabled which is the desired output but somehow it messed up and took the former days as well from the 3rd til 9th.
Here is the code I'm working with:
Here is the code in text format:
if (date >= day.day) {
return (
<Grid item key={day.id}>
<Button
key={day.id}
sx={{
color: 'white',
width: 150,
height: 150,
backgroundColor: 'primary.dark',
'&:hover': {
backgroundColor: 'primary.main',
opacity: [0.9, 0.8, 0.7],
},
}}
>
{day.day}
</Button>
</Grid>
);
} else {
return (
<Grid item key={day.id}>
<Button
// Disabled attribute for the days that haven't passed
disabled
key={day.id}
sx={{
color: 'white',
width: 150,
height: 150,
backgroundColor: 'primary.dark',
'&:hover': {
backgroundColor: 'primary.main',
opacity: [0.9, 0.8, 0.7],
},
}}
>
{day.day}
</Button>
</Grid>
);
}
Here is the code for getting the date:
Here is an example of the API I'm fetching:
Here it is again in code format:
{
"id": 1,
"day": "1",
"chocolateImage": "https://sugarfreelondoner.com/wp-content/uploads/2019/05/keto-milk-chocolate-150x150.jpg"
},
Does anybody know how to fix this? Am I doing something wrong in the code?
Thanks for any answer in advance and take care guys
CodePudding user response:
First, you don't need the if/else
statement since the only thing that changes is the disabled
prop.
You can just do this:
<Grid item key={day.id}>
<Button
disabled={date <= day.day}
key={day.id}
sx={{
color: 'white',
width: 150,
height: 150,
backgroundColor: 'primary.dark',
'&:hover': {
backgroundColor: 'primary.main',
opacity: [0.9, 0.8, 0.7],
},
}}
>
{day.day}
</Button>
</Grid>
The second thing is, in your code for date
you have a trailing /
. That will cause issues. const date = ${current.getDate()}/
can just be const date = current.getDate()
Try removing the trailing /
and see if that fixes the issue.