ReactJS - Redux form - how to conditionally show / hide an element based on a Radio Field element?
I am relatively new to Redux and I have a form that has "Yes" or "No" radio inputs. Basically, I want to conditionally show another element that contains a different reduction form field based on this radio input selection. Is there a direct way to do this?
I am trying to just check the value formProps.site_visit
, but I am getting an undefined error. For the record, I've greatly reduced the amount of code in this component for the sake of brevity.
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!
source to share
You will need formValueSelector
const selector = formValueSelector('formName');
function mapStateToProps(state, props) {
const isChecked = selector(state, 'checkboxField');
return { isChecked };
}
connect
through mapStateToProps
the rendering method will look like this.
render() {
return (
{ this.props.isChecked && (
<div>
this only shows up if the checkboxField Field is checked
</div>
) }
);
}
edit:
it looks like you are using reselect
- I have never used createStructuredSelector
and I do not understand 100% of the documentation, but a possible solution could 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
}
};
which will make up these two. I think you could also use createSelector
with mMapStateToProps
and mapStateToProps
, which I originally posted ...
source to share