Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - Date input value not updated to state

Tags:

reactjs

In my React App, I am able to set the state and update the database for all values except the date input field. My code is below:

    import React, { Component } from 'react'
    ...
    ...
    import DateInput from '../others/input/datePicker'
    ...
    ..
      change = (what, e) => this.setState({ [what]: e.target.value })

      changeDOB() {
        this.setState({ age: document.getElementByClassNames("datePicker").value })
      }

      render() {
        let {
    ...
    ...
    age,
    ...
      } = this.state
    ...
    ...
    //date of birth
    let stringAge = age.toString()
    stringAge =
      stringAge.substring(0, 4) +
      '-' +
      stringAge.substring(4, 6) +
      '-' +
      stringAge.substring(6, 8)
    ...
                    <DateInput
                      type="date"
                      change={this.changeDOB}
                      placeholder={stringAge}
                      className="datePicker"
                    />

...
...
const mapStateToProps = store => ({
  ud: store.User.user_details,
  tags: store.User.tags,
  session: store.User.session,
})

export default connect(mapStateToProps)(EditProfile)
export { EditProfile as PureEditProfile }

Here is DateInput code:

import React from 'react'
import { string, func, oneOf, bool } from 'prop-types'

const DateInput = ({ type, placeholder, ...props }) => (
  <input
    type={type}
    placeholder={placeholder}
    spellCheck="false"
    autoComplete="false"
    {...props}
  />
)

DateInput.defaultProps = {
  type: 'date',
  placeholder: '',
  disabled: false,
}

DateInput.propTypes = {
  type: oneOf(['date']),
  placeholder: string.isRequired,
  maxLength: string,
  disabled: bool,
}

export default DateInput

I tried this.change like other fields but that does not work either.

How to get the new value updated in the state ?

Note: The text is red is the value currently in the database.

enter image description here

like image 669
Kal Avatar asked Aug 03 '26 14:08

Kal


1 Answers

You need to add onChange attribute for the input field in the DateInput component as

const DateInput = ({ type, placeholder, ...props }) => (
  <input
    type={type}
    placeholder={placeholder}
    spellCheck="false"
    autoComplete="false"
    onChange = {props.Onchange}
    {...props}
  />
)

Then your main component should be as

  changeDOB(e) {
       this.setState({ age: e.target.value });
  }

  render() {
    return(
              <DateInput
                  type="date"
                  Onchange={this.changeDOB}
                  placeholder={stringAge}
                  className="datePicker"
                />
          )
             }

Please find a working example here

like image 69
Harikrishnan Avatar answered Aug 07 '26 07:08

Harikrishnan