I am new to reactjs and want to know if there is a way to check if the state value is datetime in reactjs.
What i am trying to do?
On clicking the checkbox i set its state to current date and time. But its value is not updating meaning after clicking submit button it doesnt update the checkbox....the checkbox isnot checked even though user checks it. How do i check if the value of the variable is datetime. Below is the code...Could someone help me with this. Thanks.
class Name extends React.PureComponent {
constructor(props) {
super(props);
const topic = props.topic;
this.state = {
checkbox_checked: some_value ? some_value.property : null,
};
}
handle_checkbox_change = (event) => {
this.setState({'checbox_checked': (event.target.checked === true ? timeUtils.date_to_iso_format(new Date()) : null)}, () => console.log('checkbox status:', this.state.checkbox_checked));
};
render () {
return (
<input
name="checkbox_name"
checked={state.resolved}
onChange={this.handle_checkbox_change}
type="checkbox"/>
<span>Checkbox</span>
<button type="submit">
</button>);}}
There is so many functions that helps you check if the value is a date that you can find them by a simple search. take a look here for example of some of these functions:
Check if a string is a date value
Also, you can make some changes to the code:
this.state = {
// Checkbox is either false or true so edit this according to your some_value
checkbox_checked: some_value ? true: false,
// And the date if it's checked. it can be null at initial state.
// You can set a date if you have a date.
checkbox_checked_date: null
};
And whenever your checkbox changed or user clicked on it, it means that the state should change.
So:
handle_checkbox_change = (event) => {
// checbox_checked will change whenever user clicked on checkbox
this.setState({checbox_checked: !this.state.checbox_checked, checkbox_checked_date: timeUtils.date_to_iso_format(new Date())})
};
Now everytime user clicked on checkbox your code will change the state of the checbox_checked. Then when your submiting and sending your data to some API or anywhere you might need them, just check if checbox_checked is true and if it was, then check for checkbox_checked_date, if it was null, it means that checkbox was already set to true (Your initial state - if you can't set any date for initial state otherwise you should check if the date is too behind meaning it was already checked) and if checkbox_checked_date wasn't null, it means that user changed the checkbox to true in the date you have as checkbox_checked_date and you can be sure that is for sure a date and treat it accordingly.
This way your code is way cleaner and has more features available easily for future development.
Related
I am trying to update a nested state object (checkedObjects) in a react class component, to track when checkboxes are checked and unchecked. checkedObjects has the following structure:
checkedObjects: {
[assignmentName]: boolean,
}
verifyObjects is a local variable that checks if the new name property was actually received. When I console out the contents of these objects however, checkedObjects is empty, while the new property was added to verifyObjects (see screenshot below). Can anyone advise why the state variable checkedObjects is not updating immediately?
Screenshot:
Code Snippet:
this.state = {
checkedObjects: {},
};
incrementCount(totalCount, id, checked, assignmentName) {
console.log("increment: totalCount", totalCount, " ; id:", id, checked);
// If a checkbox is clicked with an assignment name store on the checkedObjects
if (assignmentName) {
let verifyObjects = { ...this.state.checkedObjects };
verifyObjects[assignmentName] = checked;
this.setState(prevState => {
let tempObj = {...prevState.checkedObjects}
tempObj[assignmentName] = checked;
return {checkedObjects: tempObj}
});
console.log("SelectedAssignmentsObj:", this.state.checkedObjects);
console.log("VerifiedObject:", verifyObjects);
} //if
}
State updates don't occur instantaneously. When we call the setState() function, it schedules a state update. Try console logging tempObj to see the value that is being put inside of this.state.checkedObjects.
In short, your code is working the way it should but you wont be able to see the state update right after calling this.setState() [because the state update is scheduled and didnt happen at that instant]. If you want to ensure that your state did update the way you wanted, can add a dummy button on the side that console logs the value of this.state.checkedObjects or you can use the chrome extension React Developer Tools to find out the values in the state object.
In a component, I have a Calendar using react-calendar on the left side. I can add reminders via a form where I can select a date. These two dates are different displayed: the date from the react-calender is shown in the format 18/08/2021 while the date from the reminder form is shown as 2021-08-18.
How can I compare these two values so that only reminders are shown on the specific date when clicking on a calendar date? I tried to parse (which seems to be not recommended by MDN) but the output numbers are different. I tried to compare with valueOf() but the output is false.
EDIT:
I was able to compare both dates and the output is true. Therefore, I set a new prop to reminder "show" with the state of "false". But when I try to return this prop as true when both dates are the same, the prop does not change. (changing it manually with dev tools, the show/hide function works now perfectly fine).
In my index.js file, I created an onChange function when clicking a specific date in the calendar:
const onCalendarChange = (date) => {
setDate(date);
reminders.map((item) => {
const itemDate = item.date
.toLocaleString()
.slice(0, 10)
.replace(/\D/g, "");
const calDate = date.toLocaleDateString().split("/").reverse().join("");
console.log(itemDate === calDate);
if (itemDate === calDate) {
return {
...item,
show: true,
};
}
return item;
});
};
I also tried it with the filter() but this does not seem to work either. The reminders are shown the whole time.
const onCalendarChange = (date) => {
setDate(date);
setReminders(
reminders.filter(
(item) =>
item.date.toLocaleString().slice(0, 10).replace(/\D/g, "") ===
date.toLocaleDateString().split("/").reverse().join("")
)
);
};
1. First code snippet:
The first code snippet may not be working because you forgot to store the new array in a variable and reset reminders on the state using it (which you did correctly in the second code snippet).
So, the first code snippet should be something like this:
const updatedReminders = reminders.map((item) => {
// logic here
});
setReminders(updatedReminders);
2. Second Code Snippet:
Not sure why this isn't working, YET. I'll let you know when I have an update.
In the meantime, see if my suggestion for the first code snippet does the trick?
I've three buttons on the page, and when clicking on any button i want to get that selected value from the store filtered by id(done in reducer). I'm trying to use redux with mapStateToProps and mapDispatchToProps pattern, but looks like when i try to access the current selected value from the store after clicking on any button, it doesn't reflect the correct value in the console. Is this not how "this.props.anyPropValue" be used? Can you help clarify what's wrong in my example?
First time it prints default value when clicking any button, clicking again prints the previously clicked button value not the current one.
Here is a sandbox link to the simple app i created for the above
sandbox link of the code
Most of the code that you have wrote is correct, If you are expecting to see the updated output right after calling the action, it won't work
onGetCountryById(id) {
this.props.fetchCountryById(id);
console.log(this.props.country); // This will gives you the current country (We just update the state, but still that value didn't update the component)
}
try to print the value of the country in the html as below and you will see it's getting updated
{this.props.country === null ? "default" : this.props.country.name}
in the reducer you might need to do this change
case CountryActions.FETCH_COUNTRY_BY_ID:
return {
...state,
country: state.countries.find((item) => item.id === action.id) // use find instead of filter
};
and set the initial value of the country set to null
const initCountriesState = {
country: null,
countries: [
....
]
};
here is the updated sandbox
I have a form, its a pickup/address form that can have multiple pickups.
Im having trouble figuring out how to get the event.target.name of the input selected to update my state correctly.
In this case, the input names are :pickups[ 0 ].pickup_datepickups[ 1 ].pickup_date
<FieldArray name="pickups" component={this.renderpickups} />
This has a button, "add pickup" that adds another address field group ( date,city,state, etc) using the documentation of fields.push..
Everytime a new pickup is added,I call a method that re-initalizes Materialize.
How do I get the event.target.name??
initializeMaterialCss(){
let pickupdate = document.querySelectorAll(".loadPickup");
let pickupdateInstance = M.Datepicker.init(pickupdate, {
onSelect: this.handleDate,
autoClose: true
});
}
I'm using the below on the Field, and then in the materialize callback, I update redux-form date property(redux-form change method) with the parameters from this react state, and the date value I get from materialize, but it feels hacky.
If there's a better more standard way, please enlighten me.
onFocus={event => this.setState({ focused: event.target.name })}
Here is a some parts of code I am using:
class FileItem extends Component {
constructor(props) {
super(props);
// Initial state
this.state = {
hover: false,
checked: false
};
this.pickFile = this.pickFile.bind(this);
}
pickFile(e){
e.stopPropagation();
this.state.checked ? this.props.removeSelectedPaths(this.props.path) : this.props.addSelectedPaths(this.props.path);
}
//set the checked status for the checkboxes if file\folder are picked
componentWillReceiveProps(nextProps){
this.setState({checked: nextProps.selectedPaths.indexOf(this.props.path) != -1 });
}
render(){
return(
<div className='select-mode'><input id='files-select' type='checkbox' checked={this.state.checked} onClick={this.pickFile}/></div>
)
}
How this should work:
When you pick a file it should set the checked status of its checkbox. And when you use slect all files checkbox( it is not in code here) it pushes all paths to the redux state in the selectedPAths array and all files should have checked checkboxes as they are selected.
Components structure:
Files - container conencted to the redux state. Send props to FileList
FileList - dumb component wrapper for each FileItem. Sending props to FileItem.
FileItem - component which renders row for specific file
The problem:
The problem is when I use Select All files functionality the checkbox for individual file not updating the UI to show the check mark on checkbox. While picking file by file is working fine and checkbox changes to checked(but same logic is used to see if it should be checked).
Weird facts:
When I do
console.log(this.state.checked) in render it shows me that state is
true. So it should change checkbox to checked but not.
I have a similar logic for the Select All files checkbox ( it uses componentWillReceiveProps method to check if all files was selected and change the checked status) and it is working just fine.
You can reveal that the checkbox checked after you picked all files just hovering it over(which triggers on mouse enter event and changes the state which leads to re rendering). I have a feeling like a render is getting lost after state changed but the weird fact 1 tells opposite thing as we have true in state but not checked checkbox in UI.
Sometimes the component needs a key, usually when using lists. this is useful for detecting changes. Try this:
<FileItem key={file.index.toString() + file.isChecked} path={filepath} checked={file.isChecked} />
We say to react that there was a change. To re-render.
Suggest:
You must pass the checked parameter from the parent if you want to handle the status of all the items
files.map (file =>
<fileItem key={file.key} path={filepath} checked={AllChecked} />
and at FileItem:
class FileItem extends Component {
constructor(props) {
super(props);
// Initial state
this.state = {
hover: false,
checked: props.checked// <= here
};
this.pickFile = this.pickFile.bind(this);
}