Search code examples
reactjsreduxmomentjsreact-redux-formreact-datepicker

issue using custom input in Control component react-redux-form


I am trying to pass the a custom input to react-redux-form Control component, and have the value of that new input passed on submit with the values from the standard inputs.

I have a codepen example here of the issue.

DatePicker:

import React, { Component } from 'react';
import 'react-datepicker/dist/react-datepicker.css';
import DatePicker from 'react-datepicker';
import moment from 'moment';

class DatePickerInput extends Component {
  constructor (props) {
      super(props)
      this.state = {
        startDate: moment()
      };
      this.handleChange = this.handleChange.bind(this);
    }

    handleChange(date) {
      this.setState({
        startDate: date
      });
    }

  render() {
    return (
      <div>
        <DatePicker
          selected={this.state.startDate}
          onChange={this.handleChange}
        />
      </div>
      );
  }
}

export default DatePickerInput;

Form:

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Control, Form } from 'react-redux-form';
import ProgressIndicator from './ProgressIndicator';
import DatePickerInput from './DatePickerInput';

export default class SubmissionForm extends Component {
  handleSubmit(values) {
    console.log('value', values);
  }

  customInput(props) {
    return (
       <DatePickerInput {...props}/>
    );
  }

  renderDatePicker(displayName, attributeName) {
    const modelName = `newSubmission.${attributeName}`;
    return (
      <div>
          <Control
            model={modelName}
            component={this.customInput}
          />
      </div>
    );
  }

  renderStep() {
    return (
      <Form
        model="newSubmission"
        onSubmit={(data) => this.handleSubmit(data)}
      >
       <div>
          <Control.text
            className="submission-form__field-input input"
            model="newSubmission.name"
          />
      </div>
      {this.renderDatePicker('Start Date', 'startDate')}
         <button
          type="next"
         >
           submit
         </button>
      </Form>
    );
  }

  render() {
    return (
      <div className="submission-form">
        {this.renderStep()}
      </div>
    );
  }
}

SubmissionForm.propTypes = {
  handleSubmit: PropTypes.func
};

If anyone can see what is missing it would be a big help. The "Name" is passed and I can see it in the console when I submit, but for the "Start Date" is not :(


Solution

  • There is nowhere in your custom component that is actually sending the value over - it's all being kept in internal component state. You need to make sure you are sending over the changed value:

    handleChange(date) {
      this.setState({
        startDate: date
      });
      this.props.onChange(date)
    }