Skip to content

Commit 52eb712

Browse files
committed
Add Formik Connected Components as a react til
1 parent 179f5ff commit 52eb712

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
1010
For a steady stream of TILs from a variety of rocketeers, checkout
1111
[til.hashrocket.com](https://til.hashrocket.com/).
1212

13-
_814 TILs and counting..._
13+
_815 TILs and counting..._
1414

1515
---
1616

@@ -544,6 +544,7 @@ _814 TILs and counting..._
544544
- [Enforce Specific Values With PropTypes](react/enforce-specific-values-with-proptypes.md)
545545
- [Force A Component To Only Have One Child](react/force-a-component-to-only-have-one-child.md)
546546
- [Forcing A Child Remount With The Key Prop](react/forcing-a-child-remount-with-the-key-prop.md)
547+
- [Formik Connected Components](react/formik-connected-components.md)
547548
- [Formik's Validation Schema As A Function](react/formiks-validation-schema-as-a-function.md)
548549
- [Inactive And Active Component Styles With Radium](react/inactive-and-active-component-styles-with-radium.md)
549550
- [Inline Style Attributes Should Be Camel Cased](react/inline-style-attributes-should-be-camel-cased.md)
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Formik Connected Components
2+
3+
Formik comes with a `connect()` HOC that uses the context API as a way of
4+
connecting to disparate form elements. This means that form data, change
5+
handlers, touched and error data, etc. can be easily accessed without a lot of
6+
[prop drilling](https://kentcdodds.com/blog/prop-drilling).
7+
8+
Any component that lives somewhere downstream in the tree of a Formik form can
9+
use `connect()`.
10+
11+
```javascript
12+
import { connect, getIn } from "formik";
13+
14+
const Input = ({ type = "text", name, id, label, formik }) => {
15+
return (
16+
<React.Fragment>
17+
<label htmlFor={name}>{label}:</label>{" "}
18+
<input
19+
type={type}
20+
onChange={formik.handleChange}
21+
onBlur={formik.handleBlur}
22+
value={getIn(formik.values, name)}
23+
name={name}
24+
id={id}
25+
/>
26+
</React.Fragment>
27+
);
28+
};
29+
30+
export default connect(Input);
31+
```
32+
33+
This `Input` component is wrapped in `connect` which means it gets the `formik`
34+
prop which contains everything that we mentioned and more -- all the context
35+
you'll need to make your form element work.
36+
37+
You can play around with it using this [live
38+
example](https://codesandbox.io/s/quizzical-hill-7xlwi).

0 commit comments

Comments
 (0)