Skip to content

Instantly share code, notes, and snippets.

@eliseumds
Last active December 21, 2018 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eliseumds/3514afb461c73ad7a18a8b1df58abdc5 to your computer and use it in GitHub Desktop.
Save eliseumds/3514afb461c73ad7a18a8b1df58abdc5 to your computer and use it in GitHub Desktop.
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
};
@Geczy
Copy link

Geczy commented Dec 21, 2018

Update for reduxform v8?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment