Last active
December 21, 2018 19:19
-
-
Save eliseumds/3514afb461c73ad7a18a8b1df58abdc5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Update for reduxform v8?