Wednesday, January 1, 2020

bootstrap-datepicker with React: onChange doesn't fire while onClick does

bootstrap-datepicker with React: onChange doesn't fire while onClick does
import React, { Component } from 'react'
import {Redirect} from "react-router-dom";

class MyComponent extends Component {
    constructor () {
        super();
        this.state = {
     back: false,
            dateOfBirth: "",
            dateOfBirthInput: ""
        };
        this.handleUserInput = this.handleUserInput.bind(this);
    }

    componentDidMount () {
        super.componentDidMount();

        $(this.state.dateOfBirthInput).datepicker({
     format: "mm/dd/yyyy"
 });

        $(this.state.dateOfBirthInput).on('changeDate', function(e) {
            console.log(e);
            console.log(e.target.value);
     this.handleUserInput(e);
        })
    }

    handleUserInput (e) {
        let name = e.target.name;
        let value = e.target.value;

        console.log(`Name=${name}, value=${value}`);

        this.setState({[name]: value});
    }

    render () {
        if (this.state.back) {
            return <Redirect to={'/dashboard/user-profile'} push={true}/>
        }
        return (
            <div>
                <div className="form-group row">
                    <label className={'col-12 col-sm-12 col-md-4 col-lg-3 col-xl-2 col-form-label'}>Date of birth</label>
                    <div className="col-12 col-sm-12 col-md-8 col-lg-9 col-xl-10">
                        <div className='input-group date'>
                            <input name={'dateOfBirth'} value={this.state.dateOfBirth}
                                   onChange={(e) => this.handleUserInput(e)}
                                   ref={(n) => this.state.dateOfBirthInput = n}
                                   type='text' className="form-control"/>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}

export default MyComponent

No comments:

Post a Comment