I created one calendar and I don't find the solution to add one className when the date is equal "today", please see the link demo:
https://compassionate-beaver-fe6c05.netlify.com/
the code is:
https://github.com/fzabra/react-calendar/blob/master/src/Components/Calendar.jsx
The follow condition return the date today:
if (dateDay === today.getDate() && currentYear === today.getFullYear() && currentMonth === today.getMonth()) {
console.log(dateDay)
}
Observe that the console show the date of today. The square today is a it element have one id="dateDay", I think something like document.getElementById doesn't work, anybody has any ideas?
Thank you
Using the .box .green class from your CSS file, you can push the <Table.Cell> inside the if condition or else don't use the className, like so:
if (dateDay === today.getDate() && currentYear === today.getFullYear() && currentMonth === today.getMonth()) {
children.push(<Table.Cell key={j} id={dateDay} className="box green">{dateDay}</Table.Cell>)
} else{
children.push(<Table.Cell key={j} id={dateDay} className="box">{dateDay}</Table.Cell>)
This way the current date will have a green background.
Result
Full code
Related
The bounty expires in 7 days. Answers to this question are eligible for a +50 reputation bounty.
JasperMW wants to draw more attention to this question:
I've really been stuck at this problem for a few days already, and my deadline is approaching. Please help!
I've been getting "Cannot update during state transition" errors on my AutoComplete component, and after some searching around I found that it was because of my renderInput code.
I try to read the input during renderInput, but I can't edit the state then, so I can't read the input when I need to. It's all very confusing to me.
Is there a way to only execute a method when a value is really selected? EG when Enter is pressed when highlighting something, when an option in the popup is clicked, etc.
Below is the renderInput code:
public render() {
const { classes } = this.props;
return (
<div className={classes.autoSuggest}>
<Autocomplete
ListboxProps={{ style: { maxHeight: 200, overflow: 'auto' } }}
autoHighlight={true}
disablePortal={false}
options={this.getOptions()}
onClick={(_event, value) => this.onSelect(value)}
renderInput={(input) => { return this.onInput(input);}}
/>
</div>
);
}
private onInput(input: AutocompleteRenderInputParams) {
if (!this.state.alleenUnCodes &&
input.inputProps.value !== undefined &&
input.inputProps.value.toString() !== "" &&
input.inputProps.value.toString().charAt(0) === '/') {
this.setState({alleenUnCodes: true});
}
if (this.state.alleenUnCodes &&
input.inputProps.value !== undefined &&
input.inputProps.value.toString().charAt(0) !== '/') {
this.setState({alleenUnCodes: false});
}
return <TextField {...input} label={'Type GEVI/UN of /UN code (bv 20/1002, of /20)'}/>;
}
EDIT: I found the answer... I tried to read the input to filter my options. However, apparently I can just use the filterOptions param!
I apologize but I could not find an answer that helps with my problem.
I'm making a pokemon 20 questions game and recently added a new question to ask.
I'll do my best to keep it clear. But every answer is stored in state
Like this:
const [type, setType] = useState(null);
const [weakness, setWeakness] = useState(null);
const [evolve, setEvolve] = useState(null);
etc.
So I have buttons set up that assign these values as a user progresses through the game.
But my evolve question breaks the game.
Here is the function
const evolveAssign = (canEvolveBoolean) => {
setEvolve(canEvolveBoolean);
setPokemonData((prevPokeArray) => // pokemon data is a giant array of pokemon objects
prevPokeArray.filter((pokemon) => {
if (canEvolveBoolean === true) {
return pokemon.prev_evolution || pokemon.next_evolution; //checks if the properties exist. Pokemon that do not evolve, do not have such properties.
} else {
return !pokemon.prev_evolution && !pokemon.next_evolution;
}
})
)};
This is how it is being returned. Which I admit, I'm not sure if this is the best way to display questions.
{type && weakness && !evolve && (
<div>
<strong>Can your Pokemon Evolve?</strong>
<EvolveBtn mapEvolutions={mapEvolutions} onClick={evolveAssign} />
</div>
)}
The problem
When the user hits 'No' it will pass false to the function, and it does seem to work! But the question gets stuck only on "No" So I logged
<p>evolve = {evolve}</p>
and it will show 'evolve = '. So somehow, evolve is not being set at all? I haven't had this issue before with the other questions.
Is there something weird going on because it's a Boolean? Is my JS logic bad? I'm pretty much out of ideas. I apologize if this was unclear/messy. I'd love any feedback as I'm still learning.
Thank you very much.
EDIT: Created a Codesandbox here!
https://codesandbox.io/s/damp-bush-u6yel?file=/src/App.js
The error can be seen if you choose Bug -> Fire -> "No". It will break after that.
I took a look at the sandbox. Several things can be improved but I will just focus on the evolve issue.
In JavaScript null and false are falsy values. !null or !false will return true. This is why the questions are rendered incorrectly after selecting evolve.
A quick and easy fix would be to check if evolve is null or the opposite if the user already selected evolve.
{
type && weakness && (evolve === null) && (
<div style={{ fontSize: 50 }}>
<strong>Can your Pokemon Evolve?</strong>
<EvolveBtn mapEvolutions={mapEvolutions} onClick={evolveAssign} />
</div>
)
}
{/* What height? */ }
{
type && weakness && (evolve !== null) && !height && (
<div style={{ fontSize: 50 }}>
<strong>Select Height</strong>
<HeightBtn mapHeight={mapHeight} onClick={heightAssign} />
</div>
)
}
Similar checks need to be used in the rest of the conditions if you simply want to make the app work.
Using the DateRangePicker from react-dates, I wish to disable Mondays, but only during the months of July and August. React is new to me and I don't know how to start solving this problem.
The documentation has a blockedDays prop, but it is not clear to me how I should use it for my particular case.
How can I access the currently displayed month and how can I subsequently block Mondays?
For those who wish to see my code, I have made a gist.
You can achieve this by using the isDayBlocked prop.
This prop is a function callback that will send you a moment date, and require you to send a boolean back, true meaning that the day is blocked and false meaning the opposite.
According to the moment documentation, here is how you will know if your day should be blocked or not :
isDayBlocked = momentDate => {
if (momentDate.format('ddd') === 'Mon' && ['Jul', 'Aug'].includes(momentDate.format('MMM')) return true
return false
}
The following condition would work as well (refer to the doc link above) :
momentDate.format('d') === 0 && [6, 7].includes(momentDate.format('M')
Short syntax :
isDayBlocked = momentDate => momentDate.format('d') === 0 && [6, 7].includes(momentDate.format('M')
And here is the picker :
<DateRangePicker
isDayBlocked={this.isDayBlocked}
// ... your other props
/>
I think I found it. In the code you gave me, you declare the isDayBlocked prop twice :
isDayBlocked={day1 => this.state.disabledDates.some(day2 => isSameDay(day1, day2))} //First time
startDateId="datePickerStart"
endDateId="datePickerEnd"
onDatesChange={this.onDatesChange}
onFocusChange={this.onFocusChange}
focusedInput={focusedInput}
startDate={startDate}
endDate={endDate}
minimumNights={minimumNights}
isOutsideRange={condition}
isDayBlocked = {momentDate => momentDate.format('d') === 0 } // Second one
You can merge them in a single function as shown in my first bit of code and put both conditions inside :
isDayBlocked = momentDate => {
if (momentDate.format('ddd') === 'Mon' && ['Jul', 'Aug'].includes(momentDate.format('MMM')) return true
if(this.state.disabledDates.some(day2 => isSameDay(day1, day2))) return true
return false
}
Following your comment, you have 2 solutions.
Converting the values you want to test to strings :
momentDate => momentDate.format('d') === '0' && ['6','7'].includes(momentDate.format('M')
Or using the non-strict operator :
momentDate => momentDate.format('d') == 0 && ['6', '7'].includes(momentDate.format('M')
I was wondering of a good way to conditionnally render a list of items. Basically I want to render a warning message, if there's a warning, I want to render message to contain a list of all the problems, here is my current approach :
text = (
<div>Orange fields are not mandatory, are you sure you want to submit without :
<ul>
{(() => {
if (e.infos.error === "warning")
return <li>informations</li>
})()}
{(() => {
if (e.links.error === "warning")
return <li>links</li>
})()}
{(() => {
if (e.file.error === "warning")
return <li>file</li>
})()}
</ul>
</div>);
that's ugly, but I wanted to test something, so another approach I took was something like that :
function optionalWarning(props) {
if (props.error === "warning")
return <li>{props.message}</li>;
return null;
}
....
text = (
<div>Orange fields are not mandatory, are you sure you want to submit without :
<ul>
<optionalWarning error="e.infos.error" message="informations" />
<optionalWarning error="e.links.error" message="links" />
<optionalWarning error="e.file.error" message="file" />
</ul>
</div>);
This is prettier, but I don't like the fact that I have to make an external functions to do that, I suppose the best practise is the second one, but are there other ways to do that ?
Use logical operators - the right hand side of these statements will only be used if the left hand side is truthy.
Otherwise, if the left hand side is false, undefined or null, React won't render anything.
<div>Orange fields are not mandatory, are you sure you want to submit without :
<ul>
{e.infos.error === "warning" && <li>informations</li>}
{e.links.error === "warning" && <li>links</li>}
{e.file.error === "warning" && <li>file</li>}
</ul>
</div>
You have to be careful to always ensure a false, undefined or null result when your check fails - e.g. if you're checking the length of a list with {list.length && <Something/>}, when the list is empty this will evaluate to 0 and React will render it as text, whereas a check like {list.length > 0 && <Something/>} will work as you expect.
Use ternary operator for conditional rendering, it will be easy to write conditions inside JSX.
Like this:
<div>Orange fields are not mandatory, are you sure you want to submit without :
<ul>
{e.infos.error === "warning" ? <li>informations</li> : null }
{e.links.error === "warning" ? <li>links</li> : null}
{e.file.error === "warning" ? <li>file</li> : null}
</ul>
</div>
I would go for:
<ul>
{ e.infos.error === "warning" && <li>informations</li> }
{ e.links.error === "warning" && <li>links</li> }
{ e.file.error === "warning" && <li>file</li> }
</ul>
I´m developing Full Calendar like this, but instead of creating events I just get it from the database.
So now I developing Backend to receive days of the week of an event like this:
As you can see I receive booleans within days of the week
Now I want to restrict if one of this days come false, calendar doesn´t allow me to do that
JS Function:
function isGreaterThanToday(date) {
return date < hoy ? false : true;
}
function updateAssignedEvent(event, delta, revertFunc) {
if (!isGreaterThanToday(event.start)) {
mostrarError("Cant post an event today or before today.");
revertFunc();
return;
}
event.start = $.fullCalendar.moment(moment($.fullCalendar.moment(event.start.format())._i));
event.end = event.end ? $.fullCalendar.moment(moment($.fullCalendar.moment(event.end.format())._i)) : event.start;
event.color = getTareaCalendarioColor(event.tipoResponsable,
event.estatusTarea,
event.start,
event.end.diff(event.start, 'hours') <= 24 ? event.start : event.end);
updateEvent(event).then(function(data) {
if (!data.success) {
revertFunc();
return;
}
event.end = event.end !== event.start ? event.end.add(1, 'day') : event.end;
$calendar.fullCalendar('updateEvent', event);
}, function(error) {
revertFunc();
});
}
As you can see I have a function calledfunction isGreaterThanToday(date), I use it to restrict post an event today or before today. I want to do something like this, but I don´t have an idea of how can I call these booleans and compare for example Sunday of the calendar with Sunday of boolean receive. Can anyone help me there? Regards
For example into my function I add:
if (event.accion.agendarDomingo != true) {
mostrarError("Sunday is not allowed");
revertFunc();
return;
}
But how can I compare with my event.start and event.end DAY?
To get day of week using moment.js use 'e' as a format. result will be 0..6 Monday to Sunday.
event.start.format('e');
To check if the time is passed use isAfter function:
If nothing is passed to moment#isAfter, it will default to the current time.
moment(event.start).isAfter();
Now these two validation constraints combined would look like this:
function isDateValid(date) {
return date.format('e') !== "6" && moment(date).isAfter();
}