Assume that you have a form like below to add a new person:
In this example, when you select a country from the populated select list, the city select element will be populated with options based on the selected country. This form page (PersonCreationForm
) consists of below components:
The question here is this: how should I communicate the selection from CountrySelectionForm
component to CitySelectionForm
component? I have a few options in mind but I am not sure what would be the perefered way to handle this in Redux world:
PersonCreationForm
component by just hooking up the onCountrySelected
prop of CountrySelectionForm
and passing the result to CitySelectionForm
through its country
prop. No need to go through Redux for this communication. However, changing the country
prop triggers a change in CitySelectionForm
to get cities based on selected country from Redux store.PersonCreationForm
component dispatches the action indicating which country is selected. Based on that, PersonCreationForm
gets notified and passes the result to CitySelectionForm
through is country
prop. That triggers a change in CitySelectionForm
to get cities based on selected country from Redux store.PersonCreationForm
component dispatches the action indicating which country is selected. Based on that, CitySelectionForm
gets notified. That triggers a change in CitySelectionForm
to get cities based on selected country from Redux store.I would highly recommend you to use redux-form for such situations. In your case it would be something like this:
render() {
const {fields, handleSubmit} = this.props
return (
<form>
<CountrySelectInput {...fields.country}/>
<CitySelectInput {...field.city} country={fields.country.value}/>
<input type="text" {...fields.name}/>
<button type="submit" onClick={handleSubmit(this.addHandler)}>Add</button>
</form>
)
}
To make this work you should process "value" and "onChange" props in your ContrySelectInput and CitySelectInput components. Like normal inputs do.
Redux-form module will significantly simplify your life with the forms. You can do something like that with a clean redux (option 1 in your list). And it will be still right.
there is a possible way to determine which option you can use:
IF you DON'T need to share the data across the app, and components have the same parent, then you can do it with local state. Therefore it saves your time, because you dont need to write actions, reducer's code, etc. and you dont need any abstractions.
IF you need to share the data across the app, then you can use redux stuff
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With