I\'ve got a plain react-redux-powered form. I wish for there to be a form.container.tsx and a form.component.tsx, where form.container.tsx holds all the connections to redux
Here's a fully typed example that allows initializing a form using initialValues
and passing additional props (as IOwnProps
):
sampleForm.tsx:
export interface IFormData {
userId: string;
}
export interface IOwnProps {
foo: string;
}
export interface IDispatchProps {
onSubmit: (data: IFormData, dispatch: Dispatch, props: IOwnProps) => void;
}
type AllSampleFormProps = IOwnProps & IDispatchProps & InjectedFormProps;
const SampleForm: React.SFC = (props) => (
);
export const DecoratedSampleForm = reduxForm({})(SampleForm);
sampleForm.ts:
The trick here is to specify proper return type for mapStateToProps
, otherwise compiler will be complaining like other authors pointed out.
function mapStateToProps(state: AppState, props: IOwnProps): ConfigProps {
return {
form: "sampleForm", // Form will be handled by Redux Form using this key
initialValues: {
userId: state.somethere.userId // Can also be calculated using props
}
}
}
function mapDispatchToProps(dispatch: Dispatch): IDispatchProps {
return {
onSubmit: (formData: IFormData, dispatch: Dispatch, props: IOwnProps) => {
console.log(formData);
console.log(props);
}
}
}
export default connect>(
mapStateToProps,
mapDispatchToProps
)(DecoratedSampleForm);
Now this form can be mounted like this: