eliseumds
7/19/2017 - 7:36 AM

FormValueSelector.js

import React, { PureComponent, PropTypes } from 'react';
import { connect } from 'react-redux';
import { formValueSelector } from 'redux-form';

/*
  Example usage:

  * Get the value of a single form field:

  <FormValueSelector fieldName="phone">
    {phone => <CountryFlag country={getPhoneCountry(phone)} />}
  </FormValueSelector>

  * Play around with the more than one field:

  <FormValueSelector
    selector={(select, form, sectionPrefix) => Number(select('numA')) + Number(select('numB'))}
  >
    {result => <div>Result: {result}</div>}
  </FormValueSelector>

*/

@connect(
  (state, props) => {
    const { form, sectionPrefix, fieldName, selector } = props;
    const valueSelector = formValueSelector(form);

    if (typeof selector === 'function') {
      const valueSelectorBoundToState = (...args) => valueSelector(state, ...args);

      return ({
        values: selector(
          valueSelectorBoundToState,
          form,
          sectionPrefix
        )
      });
    }

    return ({
      values: valueSelector(
        state,
        sectionPrefix ? `${sectionPrefix}.${fieldName}` : fieldName
      )
    });
  }
)
class FormValueSelector extends PureComponent {
  static propTypes = {
    children: PropTypes.func.isRequired,
    values: PropTypes.any
  };

  render() {
    const { children, values } = this.props;

    return children(values);
  }
}

export default function FormValueSelectorContextContainer(props, context) {
  const { _reduxForm } = context;

  return (
    <FormValueSelector
      {...props}
      form={_reduxForm.form}
      sectionPrefix={_reduxForm.sectionPrefix}
    />
  );
}

FormValueSelectorContextContainer.contextTypes = {
  _reduxForm: PropTypes.shape({
    form: PropTypes.string.isRequired,
    sectionPrefix: PropTypes.string.isRequired
  }).isRequired
};