javascript - React + Redux: submit multi-component form -
suppose have component contains input field. second component b contains submit button. 2 components aren't linked directly (e.g 2 leaf in 2-depth tree)
on submit need retrieve input value, how resolve in react + redux environment?
the obvious solution came mind bind react component's refs redux state, in way state has reference input value (accessed through state.fieldname.input.value).
in submit button component (remember has no direct relations input component) mapstatetoprops return onclick prop function can access state , input values , can "impure" job (e.g. db request)
so code should this:
//components/testform.jsx class testform extends component { render() { return <forminput ref={(ref) => this.props.registerformfield(ref)} value=... ... /> } } //redux/actions/index.js const registerformfield = (field) => { return { type: actiontypes.register_form_field, field: field } } //redux/reducers/index.js const rootreducer = (state = {}, action) => { switch (action.type) { case actiontypes.register_form_field: var newstate = {...state}; newstate[action.field.input.name] = action.field.input; return newstate default: return state } } //containers/submitbutton.js const mapstatetoprops = (state, ownprops) => { return { text: "submit", onclick: () => { //do impure job state.fieldname.value } } } const submitbutton = connect( mapstatetoprops, mapdispatchtoprops )(formsubmitbutton) //components/formsubmitbutton.jsx class formsubmitbutton extends component { render() { return <button onclick={this.props.onclick} > {this.props.text} </button> } }
i briefly read redux-form docs , seems can't bind 2 non-related components described above (maybe i'm wrong ;) )
is there other right/elegant solution solve problem?
there no need use ref
s in case.
the idiomatic approach create form fields controlled components supplying value
property. either supplied global state (mapped in mapstatetoprops
), or state of common parent component.
you need listen changes of inputs. that, supply handler onchange
prop of input
. handler should change form data, either in redux store or in component state, depending on approach take.
this way, not matter in react application place submit button etc., long has access form data.
for working example of use case, have @ jsbin. demonstrates how separate form multiple components , keep input values in redux store without relying on ref
s.
Comments
Post a Comment