Skip to content

Commit d35e9f8

Browse files
committed
add input helper
1 parent 3611043 commit d35e9f8

File tree

2 files changed

+15
-12
lines changed

2 files changed

+15
-12
lines changed

src/components/form-library/FormLibrary.js

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,14 @@ function MyFormLibrary({ children, initialValues, onValuesChanged, onSubmit, val
1212
}
1313
}, [values]);
1414

15-
function handleChange(e) {
15+
function handleChange(name, value) {
1616
updateValues({
1717
...values,
18-
[e.target.name]: e.target.value
18+
[name]: value
1919
});
2020
updateErrors({
2121
...errors,
22-
[e.target.name]: undefined
22+
[name]: undefined
2323
});
2424
}
2525

@@ -37,11 +37,18 @@ function MyFormLibrary({ children, initialValues, onValuesChanged, onSubmit, val
3737
submitForm();
3838
}
3939

40+
function input(name) {
41+
return {
42+
value: values[name],
43+
onChange: (e) => handleChange(name, e.target.value)
44+
}
45+
}
46+
4047
const ctx = {
4148
values,
4249
errors,
43-
handleChange,
44-
handleSubmit
50+
handleSubmit,
51+
input
4552
};
4653

4754
return <FormContext.Provider value={ctx}>

src/components/form-library/index.js

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,25 +4,21 @@ import { object, string } from 'yup';
44
import MyFormLibrary, { FormContext } from './FormLibrary';
55

66
function MyForm() {
7-
const { values, errors, handleChange, handleSubmit } = useContext(FormContext);
7+
const { values, errors, handleSubmit, input } = useContext(FormContext);
88

99
return <form onSubmit={handleSubmit}>
1010
<div>
1111
<input
1212
placeholder="Email"
13-
name="email"
1413
autoComplete="off"
15-
value={values.email}
16-
onChange={handleChange}
14+
{...input('email')}
1715
/>
1816
{errors.email && <div>{errors.email}</div>}
1917
</div>
2018
<div>
2119
<input
2220
placeholder="Name"
23-
name="name"
24-
value={values.name}
25-
onChange={handleChange}
21+
{...input('name')}
2622
/>
2723
{errors.name && <div>{errors.name}</div>}
2824
</div>

0 commit comments

Comments
 (0)