0

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>);}}

1 Answers1

2

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.

Community
  • 1
  • 1
Navid Zarepak
  • 4,148
  • 1
  • 12
  • 26