I'm relatively new to Redux and I have a form that has some radio inputs "Yes" or "No". Basically, I want to conditionally show another element which contains another redux form field, based on that radio input selection. Is there a straight forward to do this?
I'm trying to just check the formProps.site_visit
value, but I get an error about it being undefined. For the record, I've greatly reduced the amount of code in this component for brevity sake.
export class RequestForm extends React.Component {
submit(formProps) {
const request = {
square_footage: formProps.get('square_footage'),
site_visit: formProps.get('site_visit'),
};
this.props.dispatch(createRequest(request));
}
// Redux Form Props.
const { handleSubmit, pristine, reset, submitting } = this.props
return (
<form className="page-form__wrapper">
<div className="page-form__block">
<div className="page-form__block">
<p> Is a site visit required to complete this request? </p>
<Field name="site_visit"
component={RadioButtonGroup}
>
<RadioButton value="true" label="Yes" />
<RadioButton value="false" label="No" />
</Field>
</div>
{this.formProps.site_visit === true &&
<div className="page-form__block">
<p> Estimate the total area of work in square feet </p>
<Field name="square_footage" component={TextField} hintText="Square Feet" />
</div>
}
</div>
</form>
);
}
Thanks in advance!
You'll need to use a formValueSelector
const selector = formValueSelector('formName');
function mapStateToProps(state, props) {
const isChecked = selector(state, 'checkboxField');
return { isChecked };
}
connect
using mapStateToProps
the render method will look like this.
render() {
return (
{ this.props.isChecked && (
<div>
this only shows up if the checkboxField Field is checked
</div>
) }
);
}
edit:
looks like you're using reselect
- I've never used createStructuredSelector
and I don't 100% understand the documentation, but a possible solution might be:
const mMapStateToProps = createStructuredSelector({
request: selectRequestForm(),
user: selectUser()
});
const mapStateToProps = (state, props) => {
return {
isChecked: selector(state, 'checkboxField'),
... mMapStateToProps(state, props) // not sure if createStructuredSelector accepts a props param
}
};
that'll compose the two. I think you could also use createSelector
with mMapStateToProps
and the mapStateToProps
I originally posted...
来源:https://stackoverflow.com/questions/42937129/reactjs-redux-form-how-to-conditionally-show-hide-element-based-on-radio-fie