-
Notifications
You must be signed in to change notification settings - Fork 833
/
ReduxForm.example.jsx
88 lines (75 loc) · 2.18 KB
/
ReduxForm.example.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import React from 'react';
import Code from '../../_shared/Code';
import { connect } from 'react-redux';
import { Grid } from '@material-ui/core';
import { reducer as formReducer } from 'redux-form';
import { createStore, combineReducers } from 'redux';
import { Provider as ReduxProvider } from 'react-redux';
import { KeyboardDatePicker } from '@material-ui/pickers';
import { reduxForm, Field, formValueSelector } from 'redux-form';
const DateField = props => {
const {
meta: { submitting, error, touched },
input: { onBlur, value, ...inputProps },
...others
} = props;
const onChange = date => {
Date.parse(date) ? inputProps.onChange(date.toISOString()) : inputProps.onChange(null);
};
return (
<KeyboardDatePicker
{...inputProps}
{...others}
format="dd/MM/yyyy"
value={value ? new Date(value) : null}
disabled={submitting}
onBlur={() => onBlur(value ? new Date(value).toISOString() : null)}
error={error && touched}
onChange={onChange}
/>
);
};
const ReduxFormExample = props => {
const formValues = {
isFormValid: props.valid,
values: {
date: props.date,
},
};
const submit = values => {
alert(JSON.stringify(values));
};
return (
// only calls the submit if form is valid
<form onSubmit={props.handleSubmit(submit)}>
<Grid container>
<Grid item container justify="center" xs={12}>
<Field name="date" component={DateField} />
</Grid>
<Grid item xs={12} sm={12} style={{ margin: '24px' }}>
<Code children={JSON.stringify(formValues, null, 2)} />
</Grid>
</Grid>
</form>
);
};
const selector = formValueSelector('example');
const mapStateToProps = state => ({
date: selector(state, 'date'),
initialValues: {
date: new Date().toISOString(),
},
});
const createReduxForm = reduxForm({ form: 'example' });
const Form = connect(mapStateToProps)(createReduxForm(ReduxFormExample));
const rootReducer = combineReducers({
form: formReducer,
// Others reducers
});
const store = createStore(rootReducer);
const App = () => (
<ReduxProvider store={store}>
<Form />
</ReduxProvider>
);
export default App;